# Problem 1003

给一序列，求和最大的子序列，如：

2
5 6 -1 5 4 -7

Case 1:
14 1 4

7 0 6 -1 1 -6 7 -5
Case 2:
7 1 6

2为序列数目。序列的一个数（5和7）是序列的元素个数。

``````#include <iostream>

using namespace std;

int main()
{
int pre, start, max, end;
int numOfInput, N;
int* input;

cin >> numOfInput;
for(int i = 0; i< numOfInput; i++)
{
cin >> N;
input = new int[N];
for(int j = 0; j< N;j++)cin >> input[j];

max = 0;
start = end = 1;
for(int n = 0; n< N; n++)
{
pre = input[n];
for(int m = n + 1; m< N; m++)
{
if(max < pre + input[m])
{
pre += input[m];
max = pre;
start = n + 1;
end = m + 1;
}
else pre += input[m];
}
}
cout << "Case " << i + 1 << ":\n";
cout << max << " " << start << " " << end;
if(i != numOfInput - 1)cout << endl << endl;
else cout << endl;
}
}``````

``````#include <iostream>
using namespace std;
int main()
{
int T,N,num,startP,endP;
cin >> T;
for(int k = 0; k< T; k++)
{
cin >> N;
int max = -1001,sum = 0,temp = 1;
for(int i = 0; i< N; i++)
{
cin >> num;
sum += num;
if(sum> max)
{
max = sum;
startP = temp;
endP = i+1;
}
if(sum< 0)
{
sum = 0;
temp = i+2;
}
}
cout<< "Case " << k+1 << ":"<< endl << max << " " << startP << " " << endP << endl;
if(k!=T-1) cout << endl;
}
return 0;
}``````

对于一般情况，这个算法比我更看清楚本质：

a1,a2,a3,a4,a5,a6

本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。