HDU 1003 Max Sum

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值