最大子段和问题

                                                    最大子段和

 

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;
}

 

全部评论

相关推荐

06-20 21:22
已编辑
门头沟学院 Java
纯真的河老师在喝茶:答应了就跑啊,实习随便跑啊,别被pua了,md就是找个廉价劳动力,还平稳过度正式工,到时候跟你说没转正
点赞 评论 收藏
分享
Lorn的意义:1.你这根本就不会写简历呀,了解太少了 2.你这些项目经历感觉真的没啥亮点啊,描述的不行,重写书写一下让人看到核心,就继续海投 注意七八月份ofer还是比较多的,越往后机会越少,抓住时机,抓紧检查疏漏,加油查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务