POJ2479 Maximum sum(dp)

题目链接

分析:

用 d1[i] 表示左向右从0到i的最大连续和,d2[i] 表示从右向左, 即从n-1到i 的最大连续和。

ans = max(ans, d1[i]+d2[i+1]), i=0,1, 2,...,n-2

直接枚举会TLE, 优化下就可AC。

 

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
#include <cstring>

using namespace std;

const int maxn = 50000+10;
const int INF = (1<<29);

int a[maxn], d1[maxn], d2[maxn];

int main() {
    int T, n;

    scanf("%d", &T);

    while(T--){
        scanf("%d", &n);

        for(int i=0; i<n;i++) {
            scanf("%d", &a[i]);
        }

        d1[0] = a[0];
        for(int i=1; i<n; i++) {
            if(d1[i-1] >= 0) d1[i] = a[i] + d1[i-1];
            else d1[i] = a[i];
        }

        d2[n-1] = a[n-1];
        for(int i=n-2; i>=0; i--) {
            if(d2[i+1] >= 0) d2[i] = a[i] + d2[i+1];
            else d2[i] = a[i];
        }

        int ans = -INF;
        int maxx = d1[0];

        for(int i=0; i<n-1; i++) {
            if(d1[i] > maxx) maxx = d1[i];
            ans = max(ans, maxx + d2[i+1]);
        }

        printf("%d\n", ans);
    }

    return 0;
}

 

posted on 2013-07-13 18:13  Still_Raining  阅读(164)  评论(0编辑  收藏  举报