Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 217257 Accepted Submission(s): 51249
Problem Description
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
Author
Ignatius.L
Recommend
一个基础dp吧,就是sum<0之前一直往前加并且取最大值。sum<0之后就从下一个数开始重新加和。
<0之前不断往前加是因为之后还有可能加上一个大于前面所有负数相加的绝对值的数字,所以不能重新开始加。比如1 2 -1 -2 5
但是<0之后就没有意义了。前面的i个数的加和小于零,后面的数不管怎么加只要带上前面所有的数,那么一定会先加上一个负数(一定会变小!)
这个题还要求记录序列的起点和终点,具体记录方式看代码吧。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int dp[100000+10];
int main()
{
int T;
int i,n,k=1;
scanf("%d",&T);
int N=T;
while(T--)
{
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&dp[i]);
int tmp=0,maxx=-1111;
int x,y,temp;
for(i=0,temp=0;i<n;i++)
{
tmp+=dp[i];
if(tmp>maxx)
{
x=i;
y=temp;
maxx=tmp;
}
if(tmp<0)
{
tmp=0;
temp=i+1;
}
}
printf("Case %d:\n%d %d %d\n",k++,maxx,y+1,x+1);
if(k!=N+1)
printf("\n");
}
return 0;
}