首页 > 代码库 > 最大子序列和
最大子序列和
public class MaxSubsequenceSum{ //第一种算法,时间复杂度为O(N^3) public int maxSubsequenceSum01(int[] array){ int maxSum = 0 ; int len = array.length ; for (int i=0;i<len;i++) { for (int j=i;j<len;j++) { int thisSum = 0 ; for (int k=i;k<=j;k++) { thisSum += array[k] ; } if (thisSum>maxSum) { maxSum = thisSum ; } } } return maxSum ; } //第二种算法,时间复杂度为O(N^2) public int maxSubsequenceSum02(int[] array){ int maxSum = 0 ; int len = array.length ; for (int i=0;i<len;i++) { int thisSum = 0 ; for (int j=i;j<len;j++) { thisSum += array[j] ; if (thisSum>maxSum) { maxSum = thisSum ; } } } return maxSum ; } //第三种算法,时间复杂度为O(NlogN) public int maxSubsequenceSum03(int[] array){ return maxSubSum(array,0,array.length-1) ; } public int maxSubSum(int[] array, int left, int right){ if(left==right){ if (array[left]>0) { return array[left] ; }else{ return 0 ; } } int center = (left+right)/2 ; int maxLeftSum = maxSubSum(array,left,center) ; int maxRightSum = maxSubSum(array,center+1,right) ; int maxLeftBorderSum = 0 ; int leftBorderSum = 0 ; for (int i=center;i>=left;i--) { leftBorderSum += array[i] ; if (leftBorderSum>maxLeftBorderSum) { maxLeftBorderSum = leftBorderSum ; } } int maxRightBorderSum = 0 ; int rightBorderSum = 0 ; for (int i=center+1;i<=right;i++) { rightBorderSum += array[i] ; if (rightBorderSum>maxRightBorderSum) { maxRightBorderSum = rightBorderSum ; } } int maxBorderSum = maxLeftBorderSum + maxRightBorderSum ; return Math.max(Math.max(maxLeftSum,maxRightSum),maxBorderSum) ; } //第四种算法(联机算法),时间复杂度为O(N) public int maxSubsequenceSum04(int[] array){ int thisSum = 0 ; int maxSum = 0 ; int len = array.length ; for (int i=0;i<len;i++) { thisSum += array[i] ; if (thisSum>maxSum) { maxSum = thisSum ; }else if(thisSum<0){ thisSum = 0 ; } } return maxSum ; }}
最大子序列和
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。