# 分治法求最大子序列和

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<set>
using namespace std;
int Max3(int i,int j,int k){
int a[3];
a[0]=i;
a[1]=j;
a[2]=k;
sort(a,a+3);
return a[2];
}
int MaxSubSum(int *a, int left, int right){
int LeftMaxSum,RightMaxSum;//存放左边、右边最大和
int MaxLeftBorderSum=0,MaxRightBorderSum=0;//存放中间向左最大和，存放中间往右最大和
int LeftBorderSum=0,RightBorderSum=0;//临时记录从中间向左、向右的和
if(left == right){//只有一个元素的情况
if(a[left]>0)
return a[left];
else
return 0;
}
int center = (left+right)/2;
LeftMaxSum = MaxSubSum(a,left,center);
RightMaxSum = MaxSubSum(a,center+1,right);

//横跨两边的最大和
for(int i = center;i>=left;i--){
LeftBorderSum += a[i];
if(LeftBorderSum > MaxLeftBorderSum)
MaxLeftBorderSum = LeftBorderSum;
}
for(int i = center+1;i<=right;i++){
RightBorderSum += a[i];
if(RightBorderSum > MaxRightBorderSum)
MaxRightBorderSum = RightBorderSum;
}
return Max3(LeftMaxSum,RightMaxSum,MaxLeftBorderSum+MaxRightBorderSum);
}
int main(){
int a[] = {4,-3,5,-2,-1,2,6,-2};
cout << MaxSubSum(a,0,7);
return 0;
}