Description
Given a set of n integers: A={a1, a2,..., an}, we define a function d(A) as below:
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.
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.
Huge input,scanf is recommended.
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
int a[50001],l[50001],r[50001];
//求[0,i]区间的最大字段和,从前向后扫描;
int gl[50001],gr[50001];
int main()
{
int N;
cin>>N;
while(N--)
{
int n;
cin>>n;
if(n<2)
break;
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
l[0]=a[0];
for(int i=1;i<n;i++)
{
if(l[i-1]<0)
l[i]=a[i];
else
l[i]=l[i-1]+a[i];
}
gl[0]=l[0];
for(int i=1;i<n;i++)
gl[i]=max(l[i],gl[i-1]);
//求[0,n-1]区间的最大字段和,从后向前扫描;
r[n-1]=a[n-1];
for(int i=n-2;i>=0;i--)
{
if(r[i+1]<0)
r[i]=a[i];
else
r[i]=r[i+1]+a[i];
}
gr[n-1]=r[n-1];
for(int i=n-2;i>=0;i--)
gr[i]=max(r[i],gr[i+1]);
int res=-100000000;
for(int i=1;i<n;i++)
{
res=max(res,gl[i-1]+gr[i]);
}
printf("%d\n",res);
}
return 0;
}