最大连续子序列

链接:http://acm.hdu.edu.cn/showproblem.php?pid=1231

思路:最大连续子序列其实可以发现开始的那个数一定不是负数,从输入开始:
ma:记录每次的最大值
res :记录每次加上输入的值后的总值,以res判定是否大于原先的最大值,如果是的话,将该点加入,判定res是否小于0,如果是的话则将res至0,并重新从下一点开始。(一开始想如果全部是负数该怎么办,但全部是负数的话,就找最大的那个负数就好了)

代码:

#include <iostream>
#include <cstdio>
using namespace std;
const int INF = -1e6;
int main()
{
    int n,a[10010];
    while(true)
    {
        cin >> n;
        if(n == 0) break;
        int res=0,st,en,Maxres=INF,tempst=0;
        for(int i=0; i<n; i++)
        {
            scanf("%d",&a[i]);
            res += a[i];
            if(res > Maxres){
                Maxres = res;
                en = i;
                st = tempst;
            }
            if(res < 0)
            {
                res = 0;
                tempst = i+1;
            }
        }
        if(Maxres < 0)
        {
            Maxres = 0;
            st=0;
            en=n-1;
        }
        printf("%d %d %d\n",Maxres,a[st],a[en]);
    }
    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值