原题:
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).
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.
题意:
输入一个长为n个数组,从中找出两个互不相交的子数组,要求两个子数组数的和要最大。
题意:
用前缀和,暴力枚举是TLE的。
此时,需要换个思路,降低时间复杂度,我们只需要遍历i从0到n,从(0,i)(i,n)两个区间找出最大的子数组和即可。
这里可以声明left数组和right数组记录i左侧的最大字段和和右侧的最大字段和。
附上AC代码:
#include<iostream>
using namespace std;
#define maxn 50010
int a[maxn];
int l[maxn];
int r[maxn];
int main()
{
ios::sync_with_stdio(false);
int t,n,i;
cin>>t;
while(t--)
{
cin>>n;
for(i=0;i<n;++i)
cin>>a[i];
l[0]=a[0];
for(i=1;i<n;++i)//记录i个数值左侧的最大字段和
{
if(l[i-1]<0)
l[i]=a[i];
else
l[i]=l[i-1]+a[i];
}
for(i=1;i<n;++i)//此时l[i]为i左边(包含i这个点)的最大字段和
l[i]=max(l[i],l[i-1]);
r[n-1]=a[n-1];
for(i=n-2;i>=0;--i)//记录i个数值右侧的最大字段和
{
if(r[i+1]<0)
r[i]=a[i];
else
r[i]=r[i+1]+a[i];
}
for(i=n-2;i>=0;--i)//此时[i]为i右边(包含i这个点)的最大字段和
r[i]=max(r[i],r[i+1]);
int ans=-10000*maxn;
for(i=1;i<n;++i)
ans=max(ans,l[i-1]+r[i]);
cout<<ans<<endl;
}
return 0;
}
欢迎评论!