poj2593 2010.2.22

poj2593 2010.2.22

Max Sequence

Time Limit: 3000MS  Memory Limit: 65536K

Total Submissions: 8745  Accepted: 3568

 

Description

Give you N integers a1, a2 ... aN (|ai|<=1000, 1 <= i <= N).


You should output S.

Input

The input will consist of several testcases. For each test case, one integer N (2 <= N <= 100000) is given inthe first line. Second line contains N integers. The input is terminated by asingle line with N = 0.

Output

For each test of the input, print a linecontaining S.

Sample Input

5

-5 9 -5 11 20

0

Sample Output

40

Source

POJ Monthly--2005.08.28,Li Haoyuan

 

题目思路:

 

        用两个数组数组记录从前和从后子序列加和的最大值,每个元素的值为从前(后)加和至该位置得到的最大值。

 

        遍历数组每个位置,找出所有位置为分界点的最大值即为结果。

 

        其中得到子序列最大和过程比较特殊,详见代码。


#include <stdio.h>
#include <string.h>

#define MIN -2000000000
#define MAXN 110000

long a[110000],front[110000],back[110000];

void main()
{
	long num,i,r,k;
	while (scanf("%d",&num),num)
	{
		for(i=1;i<=num;i++)
			scanf("%d",&a[i]);
//要记录下原始数据,否则反方向就不行了
		front[0]=MIN;
		back[num+1]=MIN;
		for(i=1;i<=num;i++)
		{
			k=(front[i-1]+a[i])>a[i]?(front[i-1]+a[i]):a[i];
			front[i]=front[i-1]>k?front[i-1]:k;
		}
		for(i=num;i>=1;i--)
		{
			  k=(back[i+1]+a[i])>a[i]?(back[i+1]+a[i]):a[i];
			  back[i]=back[i+1]>k?back[i+1]:k;
		}
		r=MIN;//刚开始赋值为0了,所以wa掉,因为可能出现全都是负数的情况
//eg:-1 -1 -1 -1 -1 结果应该是-2
		for(i=1;i<num;i++)
			if (front[i]+back[i+1]>r)
				r=front[i]+back[i+1];
		printf("%d\n",r);
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值