POJ-2479-Maximum Sum (动态规划)

原题
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;
}

欢迎评论!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值