最大字段和有很多种解法,分治递归也有其优点,这里实现一下。
时间复杂度 :n log(n)
空间复杂度O(1)没有占用额外空间
#include <iostream>
#include <math.h>
using namespace std;
int bestI = -1, bestJ = -1,bestSum = -0x3f3f3f3f;
int* a = new int[100];
int maxSum(int* a, int left, int right) {
if (left == right) {
//终止条件,更新最佳范围,返回最大值
if (a[left] > bestSum) {
bestSum = a[left];
bestI = bestJ = left;
}
return a[left];
}
else {
int center = (left + right) / 2;
int maxLeft = maxSum(a, left, center);
int maxRight = maxSum(a, center + 1, right);
//找左区间连续最大的
int temporaryBestI = center, temporaryBestJ = center+1;
int leftSum = a[center];
int temporarySum = a[center];
for (int i = center-1; i >= left; i--) {
temporarySum += a[i];
if (temporarySum > leftSum) {
leftSum = temporarySum;
temporaryBestI = i;
}
}
//找右区间连续最大的
int rightSum = a[center+1];
temporarySum = a[center+1];
for (int i = center + 2; i <= right; i++) {
temporarySum += a[i];
if (temporarySum > rightSum) {
rightSum = temporarySum;
temporaryBestJ = i;
}
}
int maxSum = max(maxLeft, max(maxRight, leftSum + rightSum));
if (maxSum > bestSum) {
bestSum = maxSum;
if (maxSum == leftSum + rightSum) {
bestI = temporaryBestI;
bestJ = temporaryBestJ;
}
}
return maxSum;
}
}
int main() {
int i = 1;
while (cin >> a[i]) {
i++;
}
cout << maxSum(a,1,i-1) << endl;
cout << bestI << endl << bestJ;
return 0;
}