Maximum Energy
Time Limit:1000MS Memory Limit:32768K
Description:
Bob wanted to increase his energy by eating AC-APPLEs. There are N(1 <= N <= 150,000) AC-APPLEs, each AC-APPLE had a magic value "v" which is a positive interger and not bigger than 500. Bob visited AC-APPLEs which are given in order, every time he faced an AC-APPLE, he can choose "eat this one" or "pass this one". The odd time Bob ate, he increase v units energy. The even time Bob ate, he decrease v units energy. Before eating any AC-APPLE, Bob's enerny is 0. Please calculate the Maximum Energy Bob can increase by eating AC-APPLEs.
Input:
The input will consist of more than one data set. Each data set has two lines. First line has an interger N. Second line has N intergers which means the magic value of each AC-APPLEs.
Output:
the Maximum Energy Bob can increase
Sample Input:
8
7 2 1 8 4 3 5 6
Sample Output:
17
問題是這樣的,以7 2 1 8 4 3 5 6爲例,若是選擇+7,則下一個數字則是-,好比+7,-2。你也能夠選擇跳過,好比+7,-1,這樣就跳過2。總之加以後一定是減,加減交錯。或者選擇跳過。最後讓你求通過這樣的運算,一串數最終能獲得的最大值。
本例中,最大值17是這麼算出來的:7-1+8-3+6=17,中間跳過了2,4和5。這道題若是用窮舉法來作天然能夠,算法效率爲O(2^N),由於每一個數字上的選擇只有2種:
1) 加/減
2) 跳過
而後在全部2^N個結果中選擇最大值便可。
可是N的最大值是150000,這種狀況下,O(2^N)的效率顯然沒法接受。這道題能夠分解成好幾個子問題,因而咱們能夠用動態規劃算法來實現算法性能的改進,使算法效率壓縮到O(N)。
咱們知道,當計算到最後一個數6時,對其採起加/減或是跳過,徹底取決於對7 2 1 8 4 3 5子序列的計算結果。
仔細概括一下,不外乎4種狀況:
1)若是前面的5是加的話,6天然是減
2)若是前面的5是減的話,後面的6天然是加
3)若是前面的5是跳過的話,那就直到找到從5開始往左數,第一個不跳過的數,好比是8(假如4,3,5都跳過)
a)若是8是加,則6減,相似狀況1)
b)若是8是減,則6加,相似狀況2)
而對於1)和3a)來講,對6的處理是同樣的,惟一不一樣的是計算到5和計算到8時的最大值是不同的。因此咱們只須要找到2者中的最大值進行處理,這樣1)和3)這兩種狀況能夠歸併爲一種。同理,2),3b)也歸併爲一種。
仍是以7 2 1 8 4 3 5 6爲例,咱們能夠基於剛纔的算法給出以下表:
其中add[index=1]=0,表示下一次0將加上2,或者跳過2;sub[index=1]=7,表示下一次,7將減去2或者跳過2。
當遍歷到2時,咱們羅列出如下4種狀況:
1) 7 – 2 = 5 (後面是add)
2) 7 跳過 2 = 7 (後面繼續是sub)
3) 0 + 2 = 2 (後面是sub)
4) 0 跳過2 = 0 (後面繼續是add)
1)和4)後面都是+,而1)的當前值是5,4)倒是0,這裏咱們要捨棄4),選擇方案1)。同理,對於2)和3),後面都是-,而2)的當前值是7,大於3)的當前值2,因此捨棄方案3)。保留下來的是1)和2),因而表變成了:
若是把行「+」用add[]存儲,把行「-」用sub[]存儲,7 2 1 8 …… 表示爲NUM[],咱們能夠將其公式化爲:
add[i] = max(sub[i-1]-NUM[i], add[i-1]) i)
sub[i] = max(sub[i-1], add[i-1]+NUM[i]) ii)
有了公式i)和ii),咱們就能夠將後面的表格填寫徹底,最終的表格爲:
由於add[i] > add[i-1],且sub[i] > sub[i-1],因此最後的最大值必定是add[N]和sub[N]中的一個。因此max(11,17) = 17。