# 算法优化之计算最大子序列的和问题

for循环穷举所有的可能

public static int maxSubSum(int [] a){
int maxSum = 0;
for (int i=0;i<a.length;i++){
for (int j = i; j <a.length ; j++) {
int thisSum = 0;
for (int k = i; k <=j ; k++){

thisSum +=a[k];
}
if(thisSum>maxSum){
maxSum = thisSum;
}
}
}
return maxSum;
}

public static int maxSubSum2(int[] a){
return maxSumRec(a,0,a.length-1);
}

private static int maxSumRec(int[] a, int left, int right) {
if(left==right){
//base case递归基例
if(a[left]>0){
return a[left];
}else{
return 0;
}
}

int center  = (left+right)/2;
int maxLeftSum = maxSumRec(a,left,center);
int maxRightSum = maxSumRec(a,center+1,right);

int maxLeftBorderSum = 0,leftBorederSum = 0;
for (int i = center; i >=left; i--) {
//求左半边的最大子序列和
maxLeftBorderSum += a[i];
if(leftBorederSum>maxLeftBorderSum){
maxLeftBorderSum = leftBorederSum;
}
}

int maxRightBorferSum=0, rightBorderSum=0;
//求右半边子序列的最大和
for (int i = center+1; i <=right; i++) {
rightBorderSum += a[i];
if(rightBorderSum>maxRightBorferSum){
maxRightBorferSum = rightBorderSum;
}

}
//返回左半边子序列、右半边子序列，左右对接子序列中的最大值
return max(maxLeftSum,maxRightSum,maxLeftBorderSum+maxRightBorferSum);
}

public static int maxSubSum3(int[] a){
int maxSum = 0,thisSum = 0;
for (int i = 0; i <a.length ; i++) {
thisSum += a[i];
if(thisSum>maxSum){
maxSum=thisSum;
}else if(thisSum<0){
thisSum=0;
}
}

return maxSum;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120