dp:maximum sum,求数组不相交子区间的最大元素和

链接:登录—专业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;
}

 细节都在代码里。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值