首页 > 其他 > 详细

51nod 最大子段和

时间:2017-08-17 09:13:07      阅读:234      评论:0      收藏:0      [点我收藏+]

N个整数组成的序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+…+a[j]的连续子段和的最大值。当所给的整数均为负数时和为0。

 
例如:-2,11,-4,13,-5,-2,和最大的子段为:11,-4,13。和为20。
简单DP  伪代码

start = 1
answerstart = asnwerend = 1
endmax = answer = a[1]
   for end = 2 to n do
        if endmax > 0 then
        endmax += a[end]
       else
       endmax = a[end]
       start = end
       endif
       if endmax > answer then
       answer = endmax
       answerstart = start
       answerend = end
       endif
  endfor

AC代码:

#include<bits/stdc++.h>
using namespace std;
int n;
const int maxn = 50005;
long long dp[maxn],a[maxn];
int main()
{
cin>>n;
for(int i=1;i<=n;i++)cin>>a[i];
int en=1,be=1;
dp[1]=1;
long long anbe=1,anen=1,enma=0,ans=1;
for(int i=1;i<=n;i++)
{
if(enma>=0)
{
enma+=a[i];
en=i;
}
else if(enma<0)
{
anbe=en;
enma=a[i];
}
if(enma>ans)
{
ans=enma;
anen=en;
anbe=be;
}
}
cout<<ans<<endl;
}

51nod 最大子段和

原文:http://www.cnblogs.com/sortmin/p/7376809.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!