package a;
/*
* 最大子序列和问题,时间复杂度O(NlogN)
*/
public class Sequence {
private static int maxSumRec(int[] a,int left,int right ){
if(left==right)
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,leftBorderSum=0;
for(int i=center;i>=left;i--){
leftBorderSum+=a[i];
if(leftBorderSum>maxLeftBorderSum)
maxLeftBorderSum=leftBorderSum;
}
//求后半部分含第一个元素的最大值
int maxRightBorderSum=0,rightBorderSum=0;
for(int i=center+1;i<=right;i++){
rightBorderSum+=a[i];
if(rightBorderSum>maxRightBorderSum)
maxRightBorderSum=rightBorderSum;
}
return max3(maxLeftSum,maxRightSum,maxLeftBorderSum+maxRightBorderSum);
}
//求最大值
private static int max3(int maxLeftSum, int maxRightSum, int q) {
// TODO Auto-generated method stub
int max;
if(maxLeftSum>maxRightSum)
max=maxLeftSum;
else
max=maxRightSum;
if(q>max)
max=q;
return max;
}
public static void main(String[] args){
int[] a={4,-3,5,-2,-1,2,6,-2};
System.out.println(maxSumRec(a, 0, a.length-1));
}
}