题目描述:
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 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.
题意:
给定一个序列,求你把序列分成两部份时的和最大值。
分析:
对于每一个i而言,都有[0, i ) 和[i, n ) 这两段 。我们分别求出每个 i 对应这两段的最大字段和,然后遍历所有的i,得到最大值即可
#include"stdio.h"
#include"string.h"
#include"algorithm"
using namespace std;
typedef long long ll;
ll a[50010];
ll pre[50010];
ll lat[50010];
ll las[50010];
int main()
{
int T;
int n;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(int i=1; i<=n; i++)
scanf("%lld",&a[i]);
memset(pre,0,sizeof(pre));
memset(lat,0,sizeof(lat));
memset(las,0,sizeof(las));
pre[0]=0;
for(int i=1; i<=n; i++)
pre[i]=max(a[i],pre[i-1]+a[i]);
ll maxx=a[n];//同样这里初始值不能为0,有可能值一开始就是小于0的。
lat[n+1]=0;
for(int i=n; i>=1; i--)
{
lat[i] = max(a[i],lat[i+1]+a[i]);
maxx = max(maxx,lat[i]);
las[i] = max(lat[i],maxx);
}
maxx=pre[1]+las[2];//初始值不能为0,因为值是有可能小于0的。
for(int i=1; i<n; i++)
{
maxx=max(maxx,pre[i]+las[i+1]);
}
printf("%lld\n",maxx);
}
}