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