目录
1.题目概述
2.两种手工运算方法
(1)分治法比大小
(2)边扫描边更新比大小
3.代码实现
(1)Algorithm 1
时间复杂度:O(N^3)
int MaxSubSum1(const vector <int> & a) {
int maxSum=0;
for (int i=0; i<a.size(); i++) // i is the left end position of the subsequence
for (int j=i; j<a.size(); j++) {// j is the position of the right end of the subsequence
int thisSum=0; // thisSum is sum of subsequence from A [i] to A [j]
for (int k=i; k<=j; k++)
thisSum+=a[k];
if (thisSum>maxSum)//If you just get this subsequence and bigger maxSum=thisSum;//Update result
}
return maxSum;
}
(2)Algorithm 2
时间复杂度:O(N^2)
int MaxSubSum2(const vector <int> & a) {
int maxSum=0;
for (int i=0; i<a.size(); i++) {
thisSum=0;
for (int j=i; j<a.size(); j++) {
thisSum+=a[j];// For the same i and different j, just accumulate 1 term on the basis of j-1 cycles
if (thisSum>maxSum)
maxSum=thisSum;
}
}
return maxSum;
}
(3)Algorithm 3
时间复杂度:O(N)
int maxSumRec (const verctor<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 j=center+1; j<=right; j++) {
rightBorderSum+=a[j];
if (rightBorderSum>maxrightBorderSum)
maxRightBorderSum=rightBorderSum;
}
return max3(maxLeftSum, maxRightSum,
maxLeftBorderSum+maxRightBorderSum);
}
int maxSubSum3 (const vector <int> & a) {
return maxSumRec(a, 0, a.size()-1);
}
(4)Algorithm 4
时间复杂度:O(N)
int MaxSubSum4(const vector <int> & a) {
int maxSum=0, thisSum=0;
for (int j=0; j<a.size(); j++) {
thisSum+=a[j];//Accumulate right
if (thisSum>maxSum)//Find bigger and update current results maxSum=thisSum;
else if (thisSum<0)//If the current subsequence sum is negative thisSum=0;//Then it ’s impossible to increase the sum of the latter part and discard it. }
return maxSum;
}