poj 2593 Max Sequence(预处理dp)

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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值