Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
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
题目大意:
给出一个长度为n的序列A[1],A[2],…,A[n],求最大连续和。也就是要求找到1<=i<=j<=n,使得A[i]+A[i+1]+…+A[j]尽量大
设S[i]=A[1]+A[2]+…+A[i],则A[i]+A[i+1]+…+A[j]=S[j]-S[i-1],当j确定时,“S[j]-S[i-1]最大”相当于“S[i-1]最小”,因此只需要扫描一次数组,维护“目前遇到过的最小S”即可。再细想一下,这题可以边输入边操作,每次只需要用到最小的S和当前的S,于是连数组空间都可以省了。。线性时间复杂度,常数空间复杂度。。代码如下
#include <stdio.h>
const int inf=0x3fffffff;
int main(){
int T,i,n,cas;
int ans,st,ed,index,min,last,curr;
scanf("%d",&T);
for(cas=1;cas<=T;cas++){
scanf("%d",&n);
index=last=min=0;
ans=-inf;
for(i=1;i<=n;i++){
scanf("%d",&curr);
curr+=last;
if(last<min)
index=i-1,min=last;
if(curr-min>ans){
ans=curr-min;
st=index+1;
ed=i;
}
last=curr;
}
printf("Case %d:\n",cas);
printf("%d %d %d\n",ans,st,ed);
if(cas!=T)
puts("");
}
return 0;
}