题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1003
2 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -5
Case 1: 14 1 4 Case 2: 7 1 6
如下代码:
for(int i = 1; i <= n; i++){ for(int j = i; j <= n; j++){ int sum = 0; for(int k = i; k <= j; k++) sum += a[k]; max = Max(max, sum); } }
for(int i = 1; i <= n; i++){ int sum = 0; for(int j = i; j <= n; j++){ sum += a[j]; max = Max(max, sum); } }
动态规划大显身手。我们记录dp[i]表示以a[i]结尾的全部子段中最大的和。我们看一下刚才想到的,我取不取a[i – 1],如果取a[i – 1]则一定是取以a[i – 1]结尾的子段和中最大的一个,所以是dp[i – 1]。 那如果不取dp[i – 1]呢?那么我就只取a[i]孤零零一个好了。注意dp[i]的定义要么一定取a[i]。 那么我要么取a[i – 1]要么不取a[i -1]。 那么那种情况对dp[i]有利? 显然取最大的嘛。所以我们有dp[i] = max(dp[i – 1]+ a[i], a[i]) 其实它和dp[i] = max(dp[i – 1] , 0) + a[i]是一样的,意思是说之前能取到的最大和是正的我就要,否则我就不要!初值是什么?初值是dp[1] = a[1],因为前面没的选了。
这样,我们的时间复杂度是O(n),空间复杂度也是O(n)——因为要记录dp这个数组。我们注意到dp[i] = max(dp[i - 1], 0) + a[i],看它只和dp[i – 1]有关,我们为什么要把它全记录下来呢?为了求所有dp[i]的最大值?不,最大值我们也可以求一个比较一个嘛。
我们定义endmax表示以当前元素结尾的最大子段和,当加入a[i]时,我们有endmax’ = max(endmax, 0) + a[i],然后再顺便记录一下最大值就好了。
老生常谈的问题来了。我们如何找到一个这样的子段?请看伪代码endmax = max(endmax, 0) + a[i], 对于endmax它对应的子段的结尾显然是a[i],我们怎么知道这个子段的开头呢? 就看它有没有被更新。也就是说如果endmax’= endmax + a[i]则对应子段的开头就是之前的子段的开头。否则,显然endmax开头和结尾都是a[i]了。说到这里是不是已经明了呢?那就看看具体的代码吧。
代码如下:
for(int i=1; i<=n; i++){ if(b>0) b+=a[i]; else b=a[i]; if(b>sum) sum=b; //sum=max(b,sum); }
#include<iostream> #define M 5000+5 #define LL long long #include<cstring> using namespace std; LL MaxSum(int n,int a[]){ LL sum=0; int b=0; for(int i=1; i<=n; i++){ if(b>0) b+=a[i]; else b=a[i]; if(b>sum) sum=b; //sum=max(b,sum); } return sum; } int main(){ int n,a[M],m; LL maxsum; while(cin>>n){ for(m=0; m<n; m++) cin>>a[m]; int b[M]; for(m=0; m<n; m++) b[m+1]=a[m]; maxsum=MaxSum(n,b); cout<<maxsum<<endl; } return 0; }