poj 2593 Max Sequence(预处理dp)
总时间限制: 3000ms 内存限制: 65536kB
描述
Give you N integers a1, a2 … aN (|ai| <=1000, 1 <= i <= N).
You should output S.
输入
The input will consist of several test cases. For each test case, one integer N (2 <= N <= 10poj 0000) is given in the first line. Second line contains N integers. The input is terminated by a single line with N = 0.
输出
For each test of the input, print a line containing S.
样例输入
5
-5 9 -5 11 20
0
样例输出
40
来源
POJ Monthly–2005.08.28,Li Haoyuan
Practice makes perfect.题做多了能力自然提高了,这个题十分类似程序设计实习2015年期末考试最后一题股票买卖。
具体做法是,既然要分段,分析数据范围发现又要
O(n)
时间复杂度计算出答案,那么枚举中间间断点以外,循环内部不能再循环计算了,也就是说必须预处理两个数组分别记录前i位最大和与i位以后最大和,这个计算也是
O(n)
的,是经典dp问题。
Accepted 2368kB 160ms 745 B G++
#define MAX_N 100000
#include<stdio.h>
#include<memory.h>
int n;
int data[MAX_N+2];
int max1[MAX_N+1],max2[MAX_N+1],temp,ans;
inline int Max(int a,int b)
{
return a>b?a:b;
}
int main()
{
while ((scanf("%d",&n)==1)&&n)
{
memset(max1,0,sizeof(max1));
memset(max2,0,sizeof(max2));
ans=0x80000000;
for (int i=1;i<=n;i++)
scanf("%d",&data[i]);
max1[0]=0x80000000;
temp=0;
for (int i=1;i<=n;i++)
{
temp=Max(data[i],temp+data[i]);
max1[i]=Max(max1[i-1],temp);
}
max2[n+1]=0x80000000;
temp=0;
for (int i=n;i>=1;i--)
{
temp=Max(data[i],temp+data[i]);
max2[i]=Max(max2[i+1],temp);
}
for (int i=1;i<n;i++)
if (max1[i]+max2[i+1]>ans)
ans=max1[i]+max2[i+1];
printf("%d\n",ans);
}
return 0;
}