子序列的和最大
阿新 • • 發佈:2019-01-12
從一個序列尋找一個連續的子序列,使得子序列的和最大。例如,給定序列 [-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;
}