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.
Output
Print exactly one line for each test case. The line should contain the integer d(A).
Sample Input1
10
1 -1 2 2 3 -3 4 -4 5 -5Sample Output13Hint
In the sample, we choose {2,2,3,-3,4} and {5}, then we can get the answer.
Huge input,scanf is recommended.
#include<iostream>
#include<cstdio>
#include<cstring>
#define INF 0x3f3f3f3f
using namespace std;
int a[50010],l[50010],r[50010];
int main()
{
int T;
cin>>T;
while(T--)
{
memset(l,0,sizeof(l));
memset(r,0,sizeof(r));
int n,d,s;
cin>>n;
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
l[1]=a[1];
for(int i=2;i<=n;i++)
{
if(l[i-1]<0) l[i]=a[i];
else l[i]=l[i-1]+a[i];
}
r[n]=a[n];
for(int i=n-1;i>0;i--)
{
if(r[i+1]<0) r[i]=a[i];
else r[i]=r[i+1]+a[i];
}
for(int i=2;i<=n;i++)
l[i]=max(l[i],l[i-1]);
for(int i=n-1;i>=1;i--)
r[i]=max(r[i],r[i+1]);
int maxn=-INF;
for(int i=1;i<n;i++)
if(l[i]+r[i+1]>maxn)
maxn=l[i]+r[i+1];
cout<<maxn<<endl;
}
return 0;
}
被这道题卡了好久,一开始写的是 l[i]=max(l[i-1],l[i]) 错的很离谱,执行时是将每个整数相加,然后我又按照课堂上的思路改了改
s=0;
for(int i=1;i<=n;i++)
{
l[i]=max(l[i-1],s+a[i]);
s+=a[i];
if(s<0) s=0;
}
后来仔细想想也不对,如果三个数都是-1,正确结果应该是-2,但因为程序有一部 if(s<0) s=0 ,结果变成了0,然后又重新改变了思路,变成了上面那样,一开始的 l [ i ] 和 r [ i ] 是以 a [ i ] 开始或结束为止(一定包括a [ i ] )的连续子序列和,但不一定是最大的,所以我又来了一部
int maxn=-INF;
for(int i=1;i<n;i++)
for(int j=i+1;j<=n;j++)
if(l[i]+r[j]>maxn)
maxn=l[i]+r[j];
但这题时间要求比较高,一旦使用二重循环就会超时,因此要想办法去掉二重循环改为
for(int i=2;i<=n;i++)
l[i]=max(l[i],l[i-1]);
for(int i=n-1;i>=1;i–)
r[i]=max(r[i],r[i+1]);
这时候的 l [ i ] 和 r [ i ] 变成了到 i 为止的最大连续子序列之和且一定是最大的,但不一定包括a [ i ] ,最后再求最大和。