HD 1003 Max Sum (最大字段和问题)
題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1003
Input The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
Output For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
Sample Input 2 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -5
Sample Output Case 1: 14 1 4Case 2: 7 1 6
思路一: 剛開始的第一反應就是枚舉,枚舉一個開頭位置i,一個結尾位置j>=i,再求a[i..j]之間所有數的和,找出最大的就可以啦。當然代價也是很高的O(N^3)。
如下代碼:
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]; elseb=a[i]; if(b>sum)sum=b; //sum=max(b,sum);}下面就此題貼出完整代碼:
總結
以上是生活随笔為你收集整理的HD 1003 Max Sum (最大字段和问题)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据结构之二叉树的先序、中序、后续的求法
- 下一篇: HDOJ 2049 不容易系列之(4)—