hdu 1003 最大连续子串和 [dp]

Max Sum

hdu 1003 Max sum

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的数组,然后求出最大的连续子串的和,并且输出这个子串的开始和结束位置。

解题思路:

输入一个数组,先判断他的最大值是否为非正数,如果是的话,直接输出最大值并记录其下标即可,因为要输出对应位置,所以数组读入的时候我从1开始,直接输出下标就好了,对于有正有负的情况下,进行判断处理,先定义一个sum表示处理的子串的大小,再定义一个max表示最大的子串和。如果sum值加上新读入的一个数据后小于0时,这个数就可以直接放弃,sum=0,进行下一个数据的读取,否则的话就最大子串就添加这个数,sum+=a[i];然后判断max是否大于sum,小于等于情况下就更新max,更新max时记录此时下标为欲求子串的右下标,而左下标就是在sum更新的时候更新左下标就好了,最后输出max 就行。

#include <stdio.h>
#include <string.h>
int a[100100];

int main()
{
    int t,n,i,j,l,r,v,s,max,sum;
    scanf("%d",&t);
    for(s=1;s<=t;s++)
    {
        if(s!=1)
            printf("\n");
        scanf("%d",&n);
        max=-1010;
        for(i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            if(max<a[i])
            {
                max=a[i];
                l=i;    
            }
        }
        if(max<=0)
            printf("Case %d:\n%d %d %d\n",s,max,l,l);
        else
        {
            sum=0;
            max=-1010;
            l=r=v=1;
            for(i=1;i<=n;i++)
            {
                if(a[i]+sum<0)
                {
                    sum=0;
                    l=i+1;
                }
                else
                    sum+=a[i];
                if(max<=sum)
                {
                    max=sum;
                    r=i;v=l;
                }
            }
            printf("Case %d:\n",s);
            printf("%d %d %d\n",max,v,r);
        }    
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值