链接:登录—专业IT笔试面试备考平台_牛客网
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).
一个方法是,用两个dp数组来维护两个区间的最大元素和,为了保证不相交,我们可以让a【i】求以mas【i】为终点的最大区间和,b【i】求以mas【i】 为起点的最大区间和,然后一次循环求出最大的a【i】并加上其下一个b【i】即可;
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
#define ll long long
ll n,t;
ll mas[50010]={0},a[50010],b[50010];
inline int read()
{
char ch=getchar(); int nega=1; while(!isdigit(ch)) {if(ch=='-') nega=-1; ch=getchar();}
int ans=0; while(isdigit(ch)) {ans=ans*10+ch-48;ch=getchar();}
if(nega==-1) return -ans;
return ans;
}
int main()
{
t=read();
while(t--){
n=read();
for(int i=1;i<=n;++i) {mas[i]=read();a[i]=mas[i];b[i]=mas[i];}
// b[n]=mas[n];
// a[1]=mas[1];
for(int i=2;i<=n;i++){
a[i]=max(mas[i],a[i-1]+mas[i]);
}
for(int i=n-1;i;i--){
b[i]=max(mas[i],b[i+1]+mas[i]);
}
ll sum=-0x3f,maxn=-0x3f;
for(int i=1;i<n;++i){//这里不能取到n,不然b【n+1】会有影响!!!
maxn=max(maxn,a[i]);
sum=max(sum,maxn+b[i+1]);
}
cout<<sum<<"\n";
}
//两个dp数组的求出应该要放到两个循环里,因为数据范围比较大,最后一个求sum的过程也是o(n)的,
//因为每一次的maxn都能保证是当当前最大的,然后与下一个b【i+1】相加,
//以及,要快读。。。
return 0;
}
细节都在代码里。