We have a lot of ways to solve the maximum subsequence sum problem and different ways take different time.
1, Brute-force algorithm
int maxSubSum1 (const vector<int> &a) {int maxsum=0;for (int i=0;i<a.size (); i++) for (int j=i;j<a.size (); J + +) {int sum=0;for (int k=i;k<=j;k++) sum+=a[k];if (sum>maxsum) maxsum=sum;} return maxsum;} /*the Running time is O (n^3) It takes too much time.*/
2, a little imporvement
int maxSubSum2 (const vector<int>& a) { int maxsum=0; for (int i=0;i<a.size (); i++) { int sum=0; for (int j=i;j<a.size (); j + +) { sum+=a[j]; if (maxsum<sum) { maxsum=sum;}} } return maxsum;}
3. Divide-conquer algorithm
We can divide this problem into three parts:
(1) first half;
(2) cross the middle parts;
(3) second part;
What we need to does is to find the max sum of the three part.
int max3 (int a, int b, int c) {if (a>b) {if (a>c) return a;else return C;} Else{if (c>b) return c;else return B;} int maxSubSum3 (cosnt vector<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 maxleftbodersum=0, leftbodersum=0;for (int i=center;i>=left;i--) {leftbodersum+=a[i];if (leftBoderSum> maxleftbodersum) Maxleftbodersum=leftbodersum;} int maxrightbodersum=0, leftbodersum=0;for (int i=center+1;i<=right;i++) {rightbodersum+=a[i];if (rightBoderSum >maxrightbodersum) Maxrightbodersum=rightbodersum;} Return Max3 (Maxleftsum, maxleftbodersum+maxrightbodersum,maxrightsum);}
4. The best algorithm
If the start is negative, the sum of the subsequence can isn't being the max. Hence, any negative subsequence cannot possibly is a prefix of the optimal subsequence.
int maxSubSum4 (const vector<int> & a) {int maxsum=0, sum=0;for (int i=0;i<a.size (); i++) {sum+=a[i];if (sum >maxsum) Maxsum=sum;else if (sum<0) sum=0;} return maxsum;}
Maxmum subsequence sum problem