Maximum sum
Accept:247 | Submit:825 |
Time Limit:1000MS | Memory Limit:65536KB |
Description
Given a set of n integers: A={a1, a2,..., an}, we define a function d(A) as below:
d(A)=sum{a[s1]~a[t1]}+sum{a[s2]~a[t2]}
The rule is 1<=s1<=t1<s2<=t2<=n.
Your task is to calculate d(A).
Input
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.
Output
Print exactly one line for each test case. The line should contain the integer d(A).
Sample Input
1
10
1 -1 2 2 3 -3 4 -4 5 -5
Sample Output
13
Hint
In the sample, we choose {2,2,3,-3,4} and {5}, then we can get the answer.
Huge input,scanf is recommended.
求一個數列中兩個不相交的連續子段的最大和。從0~n-1掃一遍,求掃到第i個元素時的最大子段和,然後從n-1~0掃一遍求掃到第j個元素時的最大字段和,然後計算dp1[i]+dp2[j]的最大值(i+1=j)。這裡節省空間把dp2省掉了,掃到第j項時計算一下dp[j-1]和目前max的值就可以了
#include<cstdlib>
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#define L 50050
#define ll long long
#define inf -999999999
using namespace std;
int a[L],dp[L],t,i,ans,n,Max,sum;
int main(){
for(scanf("%d",&t);t--;){
scanf("%d",&n);
sum=0;
Max=inf;
for(i=0;i<n;i++){
scanf("%d",&a[i]);
sum+=a[i];
if(sum>Max)Max=sum;
if(sum<0)sum=0;//a[i]可能是負數
dp[i]=Max;
}
sum=0;Max=ans=inf;
for(i=n-1;i>=1;i--){
sum+=a[i];
if(sum>Max)Max=sum;
if(sum<0)sum=0;
if(Max+dp[i-1]>ans)ans=Max+dp[i-1];
}
printf("%d\n",ans);
}
return 0;
}