描述
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
思路
如果直接用前一遍,后一遍,然后再计算确实会超时。
然后参考了另一个博主的思路。链接:https://blog.csdn.net/qq_26919935/article/details/77993092
再开两个数组存储在i前面的最大dp,和在i后面的最大dp这样最后只需要用一重循环就可以直接得到最大结果,简单又完美的解决了超时问题。厉害。。我的脑子怎么想不到,别熬夜了,再熬就傻了。
代码
#include <bits/stdc++.h>
using namespace std;
int num[50005];
int dp[50005],a[50005];
int pd[50005],b[50005];
int main(){
int k;
cin>>k;
while(k--){
int n;
cin>>n;
memset(dp,0,sizeof(dp));
memset(pd,0,sizeof(pd));
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
for(int i=1;i<=n;i++) cin>>num[i];
a[0]=num[1];
b[n+1]=num[n];
for(int i=1;i<=n;i++){
dp[i]=max(dp[i-1]+num[i],num[i]);
a[i]=max(a[i-1],dp[i]);
}
for(int i=n;i>=1;i--){
pd[i]=max(pd[i+1]+num[i],num[i]);
b[i]=max(b[i+1],pd[i]);
}
int maxn=-999999;
for(int i=2;i<=n;i++){
maxn=max(a[i-1]+b[i],maxn);
}
cout << maxn <<endl;
}
return 0;
}