Maximum sum——dp

描述

Given a set of n integers: A={a1, a2,…, an}, we define a function d(A) as below:

                t1     t2 
    d(A) = max{ ∑ai + ∑aj | 1 <= s1 <= t1 < s2 <= t2 <= n }
               i=s1   j=s2

Your task is to calculate d(A).

输入

The input consists of T(<=30) test cases. The number of test cases (T) is given in the first line of the input.
Each test case contains two lines. The first line is an integer n(2<=n<=50000). The second line contains n integers: a1, a2, …, an. (|ai| <= 10000).There is an empty line after each case.

输出

Print exactly one line for each test case. The line should contain the integer d(A).

样例

  • Input
    1
    10
    1 -1 2 2 3 -3 4 -4 5 -5
  • Output
    13

题解

  • 题意就是给一个序列,找其中两个不相交的子串s1、s2,使得s1+s2最大
  • 用dpl[i]表示以i为结尾的最大子串和,用dpr[i]表示以i为开头的最大子串和,再用一个dpres[i]表示在i后面(包括i)的最大子串和,即max(dpr[j] (i <= j < n))。
    状态转移方程:
    dpl[i]=max(dpl[i-1]+num[i],num[i]);
    dpr[i]=max(dpr[i+1]+num[i],num[i]);
    dpres[i]=max(dpres[i+1],dpr[i]);

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include<bits/stdc++.h>
#define INIT(a,b) memset(a,b,sizeof(a))
#define LL long long int
using namespace std;
const int MAX=0x7fffffff;
const int MIN=-0x7fffffff;
const int INF=0x3f3f3f3f;
const int Mod=1e9+7;
const int MaxN=1e7+7;
int dpl[50005],dpr[50005],num[50005],dpres[50005];
int main(){
//freopen("1.in","r",stdin);
//freopen("1.out","w",stdout);
int T;scanf("%d",&T);
while(T--){
INIT(dpl,0);INIT(dpr,0);INIT(dpres,0);
int n;scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&num[i]);

dpl[1]=num[1],dpr[n]=dpres[n]=num[n];
for(int i=2;i<=n;i++)
dpl[i]=max(dpl[i-1]+num[i],num[i]);
for(int i=n-1;i>=1;i--){
dpr[i]=max(dpr[i+1]+num[i],num[i]);
dpres[i]=max(dpres[i+1],dpr[i]);
}

int ans=MIN;
for(int i=2;i<=n;i++)
ans=max(dpres[i]+dpl[i-1],ans);
printf("%d\n",ans);
}
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值