版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zpalyq110/article/details/80086617
从一个序列寻找一个连续的子序列,使得子序列的和最大。例如,给定序列 [-2, 1, -3, 4, -1, 2, 1, -5, 4],连续子序列 [4, -1, 2, 1] 的和最大,为 6
思路:此题从头开始遍历,用res记录下标begin开始到目前的和,用maxRes记录最大的res。当maxRes更新时,更新end(end = i)和begin(begin = tempbegin);当res小于0时,重新记录res(将res置0),同时记录新res的开始位置tempbegin。
代码:
#include <iostream>
using namespace std;
int * subMax(int arr[], int len) {
int res = 0;
int maxRes = -9999999;
int begin = 0;
int end = 0;
int tempbegin = 0;
for (int i = 0; i < len; i++) {
res = res + arr[i];
if (res > maxRes) {
maxRes = res;
end = i;
begin = tempbegin;
}
if (res < 0) {
res = 0;
tempbegin = i + 1;
}
}
int * r = new int[3];
r[0] = maxRes;
r[1] = begin;
r[2] = end;
return r;
}
int main() {
int a[] = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };
int len = 9;
int *res = subMax(a, len);
cout << "最大和为:" << endl;
cout << res[0] << endl;
cout << "此子序列为:" << endl;
for (int i = res[1]; i < res[2]; i++) {
cout << a[i] << " ";
}
cout << endl;
system("pause");
return 0;
}