Max Sequence

题目链接:http://acm.tzc.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=2891

Max Sequence

Time Limit(Common/Java):3000MS/9000MS     Memory Limit:65536KByte
Total Submit: 75            Accepted: 20

Description

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 Input

5
-5 9 -5 11 20
0

Sample Output

40
分析:最大m子段问题,此题中m=2。方法还是DP,基本上还是用我们熟悉的最大子段和的方法。读入数据是时做一次DP,得到从前往后到第i(0=<i<n)个元素处时
的最大子段和,然后再从后往前反向做一次DP,加上前面求得的正向的最大字段和即可求出一个最大值。
代码:
View Code
#include<stdio.h>
const int MAXN=100005;
const int INF=1<<28;
int main()
{
int n;
while (scanf("%d", &n), n)
{
int lmax[MAXN], a[MAXN];
int i;
for (i=0; i<n; i++)
{
scanf(
"%d", &a[i]);
}
int nStart=a[0];
int nAll=a[0];
lmax[
0]=a[0];
for (i=1; i<n; i++)
{
if (nStart<0) nStart=0;
nStart
+=a[i];
if (nStart>nAll) nAll=nStart;
lmax[i]
=nAll;
}
int max=-INF;
nStart
=-INF;
nAll
=-INF;
for (i=n-1; i>=1; i--)
{
if(nStart<0) nStart=0;
nStart
+=a[i];
if (nStart>nAll) nAll=nStart;
if (nAll+lmax[i-1]>max) max=nAll+lmax[i-1];
}
printf(
"%d\n", max);
}
return 0;
}

posted on 2011-04-05 22:54  tzc_yujunyong  阅读(359)  评论(0)    收藏  举报