1481:Maximum sum

1481:Maximum sum

总时间限制: 
1000ms
 
内存限制: 
65536kB
描述
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).
样例输入
1

10
1 -1 2 2 3 -3 4 -4 5 -5
样例输出
13



//最大连续和的变种,dp数组表示以i结尾的子串最大和,l数组表示i往左最大的一个和,后二者表示反过来
#include<iostream>
#include<memory.h>
using namespace std;
int dp[50001], rdp[50001], l[50001], r[50001], data[50001];
int main() {
int T; scanf("%d", &T);
while (T --) {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i ++) scanf("%d", &data[i]);
dp[0] = data[0]; rdp[n - 1] = data[n - 1];
memset(l, 0, sizeof(l));
memset(r, 0, sizeof(r));
l[0] = dp[0]; r[n - 1] = rdp[n - 1];
for (int i = 1; i < n; i ++) {
dp[i] = data[i];
if (dp[i - 1] > 0) dp[i] += dp[i - 1];
l[i] = max(l[i - 1], dp[i]);
}
for (int i = n - 2; i >= 0; i --) {
rdp[i] = data[i];
if (rdp[i + 1] > 0) rdp[i] += rdp[i + 1];
r[i] = max(r[i + 1], rdp[i]);
}
int ans = -2147483646;//注意全为负数的情况
for (int i = 0; i < n - 1; i ++)
ans = max(ans, l[i] + r[i + 1]);
printf("%d\n", ans);
}
}



posted @ 2017-09-16 22:05  StillLife  阅读(309)  评论(0编辑  收藏  举报