Max Sequence (DP)

Give you N integers a1, a2 ... aN (|ai| <=1000, 1 <= i <= N).


You should output S. 

input 

The input will consist of several test cases. For each test case, one integer N (2 <= N <= 100000) is given in the first line. Second line contains N integers. The input is terminated by a single line with N = 0.

output

For each test of the input, print a line containing S.

sample input

5
-5 9 -5 11 20
0

sample output

40

最大m子段问题,此题中m=2。主要方法还是DP,其实理解题意以后代码的编写不是很困难,就是这道题目很难理解,数学弱鸡瑟瑟发抖。

基本上还是用我们熟悉的最大子段和的方法。读入数据是时做一次DP,
得到从前往后到第i(0=<i<n)个元素处时的最大子段和,然后再从后往前反向做一次DP,
加上前面求得的正向的最大字段和即可求出一个最大值。

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int inf=-0x3fffffff;
int num[100001], dp[100001];
int main()
{
    int n,max,sum,s;
    while(scanf("%d",&n))
    {
        if(n==0)
        break;
		sum=0;
        max=inf;
        for(int i=1;i<=n;i++)
        {
            scanf("%d", &num[i]);
            sum +=num[i];
            if(sum>max)
                max=sum;
            dp[i]=max;
            if(sum<0)
                sum=0;
        }
        dp[0]=s=max=inf;
        sum=0;
        for(int i=n;i>0;i--) 
        {
            sum+= num[i];
            if(sum>max)
                max=sum;
            if(s<max+dp[i-1])
                s=max+dp[i-1];
            if(sum<0)
                sum=0;
        }
        printf("%d\n",s);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值