【问题】
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).【输入】
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.【输出】
Print exactly one line for each test case. The line should contain the integer d(A).
【思路】
这道题是题意是求最大两子段和
两边dp,一遍从左一遍从右,表示前i和后i的最大子段值,最后查找left[i]+right[i+1]最大值即可
很基础的一道题,看代码吧,还有一点要注意,这里要用scanf和printf,用cin cout会超时
【源代码】
#include<iostream>
#include<cstdio>
#include<string>
#include<cstdlib>
#include<cmath>
using namespace std;
#include<stack>
#include<cstdlib>
#include<string>
#include<cstdio>
#include<cstring>
#include<iomanip>
#include<algorithm>
#include<map>
#define ll long long
int a[50010],l[50010],r[50010];
int main()
{
int t,n,maxx;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
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];
}
//这里处理一下,保证当前值是最大子段的和(比如当前值为负数,他的值虽然大于0但是最大值是l[i-1])
for(int i=1;i<n;i++)
l[i] = max(l[i-1],l[i]);
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];
}
for(int i=n-2;i>=0;i--)//同理
r[i]=max(r[i],r[i+1]);
maxx = -9999999;
for(int i=0;i<n-1;i++)
maxx = max(maxx,l[i]+r[i+1]);
printf("%d\n",maxx);
}
return 0;
}