Max Sum
Given a sequence a[1],a[2],a[3]…a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
Output
For each test case, you should output two lines. The first line is “Case #:”, # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
Sample Input
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
Sample Output
Case 1:
14 1 4
Case 2:
7 1 6
思路:
先定义一个很小的数(maxx),然后用for循环将a[i]相加,每加一次就和sum比较一次,遍历比较输出最大的maxx。
代码实现:
#include<cstring>
#include<algorithm>
using namespace std;
int a[100005];
int main()
{
int t;
cin>>t;
int c=t; //计数器,用来记case后面的那个数字
while(t--)
{
int n;
int maxx=-10000000; //先把maxx定为一个特别小的数
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
int k=1; //子序列开始的地方(计数器)
int sum=0; //子序列的和
int s,e; //start end
for(int i=1;i<=n;i++)
{
sum+=a[i];
if(sum>maxx)
{
maxx=sum;
s=k;
e=i;
}
if(sum<0) //如果一直为负数就把sum重新归零,直到有正数为止
{
sum=0;
k=i+1; //开始位置也+1
}
}
printf("Case %d:\n",c-t); //c为最开始的t,因为是t组输入所以,每次t都减1。c-t就是case后面的数字
cout<<maxx<<" "<<s<<" "<<e<<endl;
if(t!=0) //每组样例中间用一个空行隔开,最后一个样例没有
{
printf("\n");
}
}
return 0;
}