#include <iostream>
using namespace std;
int MaxSubsequenceSum1(int* array,int left,int right); //O(nlogn)
int MaxSubsequenceSum2(int* array,int left,int right); //O(n)
int MaxBorderSum(int* array,int begin,int end);
int MaxThreeNum(int x,int y,int z);
int array[8]={4,-3,5,-2,-1,2,6,-2};
int main()
{
cout << MaxSubsequenceSum2(array,0,9) << endl;
if(cin.get()=='\n')
return 0;
}
int MaxSubsequenceSum1(int* array,int left,int right)
{
if(left==right)
return array[left];
int center=(left+right)/2;
int LeftMaxSum=MaxSubsequenceSum1(array,left,center);
int RightMaxSum=MaxSubsequenceSum1(array,center+1,right);
int TheMaxBorderSum=MaxBorderSum(array,center,left)+MaxBorderSum(array,center+1,right);
return MaxThreeNum(LeftMaxSum,RightMaxSum,TheMaxBorderSum);
}
//动态规划思想:
int MaxSubsequenceSum2(int* array,int left,int right)
{
int ThisSum=0,MaxSum=0;
for(int i=left;i<=right;++i)
{
ThisSum+=array[i];
if(ThisSum<0)
ThisSum=0;
else if(ThisSum>MaxSum)
MaxSum=ThisSum;
}
return MaxSum;
}
int MaxBorderSum(int* array,int begin,int end)
{
int MaxBorderSum=0,BorderSum=0,MoreOrLess=0;
if(begin==end)
return array[begin];
else if(begin<end)
MoreOrLess=1;
else if(begin>end)
MoreOrLess=-1;
int TheEnd=end+MoreOrLess;
for(int i=begin;i!=TheEnd;i+=MoreOrLess)
{
BorderSum+=array[i];
if(BorderSum>MaxBorderSum)
MaxBorderSum=BorderSum;
}
return MaxBorderSum;
}
int MaxThreeNum(int x,int y,int z)
{
return x>y?(x>z?x:z):(y>z?y:z);
}