zoukankan      html  css  js  c++  java
  • 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
    ", ans);
        }
    
        return 0;
    }
  • 相关阅读:
    [Swift]LeetCode900. RLE 迭代器 | RLE Iterator
    TNS-12508 When Issuing Any SET Command For The Listene
    shell getopts
    archive log full ora-00257
    php 验证码
    php 缩略图
    弧度
    php输出中文字符
    流程图
    windows clone 迁移数据库
  • 原文地址:https://www.cnblogs.com/tanhehe/p/3188197.html
Copyright © 2011-2022 走看看