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