HDU-1003-Max Sum(dp经典问题-最大连续子序列和+一个数组解决)

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

个人分析:
这个题目意思就是求最大连续子序列和,并且还要确定你取的数字起始位置和结束位置(从1开始计数)所以我们后面的得到的结果要+1 核心代码如下:

if(sum+a[i]>=a[i])
{
     sum+=a[i];
     last=i;
}
else
{
     sum=a[i];
     first=last=i;
}

对以上代码的解释:
状态转移方程,max( dp[ i - 1 ] + a [ i ] , a [ i ] )
从这个状态转移方程,我们就可以想到:
相加后大于该点的值,则加入当前连续段,更新该点为终点
相加后小于该点的值,则结束当前连续段,更新该点为起点、终点
其实这样相当于求出了很多个sum值,然后通过中间变量ans比较 找到那个最大的sum赋值给ans 然后输出ans

个人感受:
我看别人大佬的博客代码里面有两个数组,多了一个dp数组,很明显这个题要用动态规划才能解。但是后面想了想觉得没必要两个数组,具体看分析~
具体代码如下:
AC

#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=100000+8,INF=0x7f7f7f7f;
int a[maxn];
int main()
{
    int t,k=0;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        for(int i=0;i<n;i++)
        {
            cin>>a[i];
        }
        int sum=0,ans=-INF;
        int first=0,last=0;
        int x=0,y=0;
        for(int i=0;i<n;i++)
        {
            if(sum+a[i]>=a[i])
            {
                sum+=a[i];
                last=i;
            }
            else
            {
                sum=a[i];
                first=last=i;
            }
            if(sum>ans)
            {
                ans=sum;
                x=first;
                y=last;
            }
        }
        printf("Case %d:\n",++k);
        printf("%d %d %d\n",ans,x+1,y+1);
        if(t)
        {
            cout<<endl;
        }
    }

    return 0;
}

学如逆水行舟,不进则退
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一百个Chocolate

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值