您的位置:首页 > 其它

Maximum sum-动态规划

2015-07-25 17:14 351 查看


A - Maximum sum
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d
& %I64u
Submit Status Practice POJ
2479

Description

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.
/*
Author: 2486
Memory: 544 KB		Time: 438 MS
Language: C++		Result: Accepted
*/
//题目思路是从左到右分别求出它们所在位置的最大连续和,然后从右到左求出它们所在的最大连续和
//接着就是a[i]+b[i+1],a数组代表着从左到右,b代表着从右到左所以不断的比较a[0]+b[1],a[1]+b[2]求最大值即可
//怎样求解最大值(代码最后段有详解)
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=50000+5;
int n,m;
int a[maxn];
int dp[maxn];
int main() {
scanf("%d",&n);
while(n--) {
scanf("%d",&m);
for(int i=0; i<m; i++) {
scanf("%d",&a[i]);
}
dp[0]=a[0];
int sum=a[0];
int ans=a[0];
for(int i=1; i<m; i++) {
if(sum<0) {
sum=0;
}
sum+=a[i];
if(sum>ans) {
ans=sum;
}
dp[i]=ans;
}
sum=a[m-1];
int Max=dp[m-2]+sum;
ans=a[m-1];
for(int j=m-2; j>=1; j--) {
if(sum<0) {
sum=0;
}
sum+=a[j];
if(sum>ans) {
ans=sum;
}
Max=max(Max,dp[j-1]+ans);
}
printf("%d\n",Max);
}

return 0;

}


如果当前的数据和小于零,很明显,将它加入到后面的计算中,肯定会减少最大值

很简单的道理,-1+4<0+4,如果之前的取值小于零,抛弃它,重新赋值为零

然后通过maxs不断更新当前的最大值

while(true){

scanf("%d",&a);

if(sum<0) {

sum=0;

}

sum+=a;

if(sum>maxs) {

maxs=sum;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: