最大子段和问题

                                                    最大子段和

 

N个整数组成的序列a11,a22,a33,…,ann, 求该序列如aii+ai+1i+1+…+ajj的连续子段和的最大值。当所给的整数均为负数时和为0。

例如:-2,11,-4,13,-5,-2,和最大的子段为:11,-4,13。和为20。

Input

第1行:整数序列的长度N(2 <= N <= 50000) 
第2 - N + 1行:N个整数(-10^9 <= Aii <= 10^9)

Output

输出最大子段和。

Sample Input

6
-2
11
-4
13
-5
-2

Sample Output

20

思路其实很简单,自己拿笔照着程序模拟一下就会很明白。

//#include <bits/stdc++.h>
#include <stdio.h>
#include <algorithm>
#include <string.h>
using namespace std;
typedef long long LL;
const int MAXN = 50000+10;
LL dp[MAXN];
LL num[MAXN];

int main()
{
    int n;
    while( scanf("%d", &n) != EOF )
    {
        memset(dp, 0, sizeof(dp));
        bool flag = false;
        for( int i=1; i<=n; i++ )
        {
            scanf("%lld", &num[i]);
            if( num[i] > 0 )
                flag = true;
        }
        if( !flag )
            printf("%d\n", 0);
        else
        {
            LL temp = 0;
            //LL dp = 0;
            for( int i=1; i<=n; i++ )
            {
                if( temp > 0 )
                    temp += num[i];
                else
                    temp = num[i];
                //if( temp > dp[i] )
                //    dp[i] = temp;
                dp[i] = max(dp[i-1], temp);
            }
            printf("%lld\n", dp[n]);
        }
    }

    return 0;
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值