This is combination of II and III.

1. when k >= length, it is totally II.

2. when k < length, it is another III. A localMaximum and globalMaximum subarray need to be maintained. But we can reduce the two dimensional DP to one dimensional DP

localMax[i][j] = max(local[i-1][j] + diff, globalMax[i-1][j-1] + max(0, diff))    ==>    localMax[j] = max(localMax[j] + diff, globalMax[j-1] + max(0, diff))

globalMax[i][j] = max(globalMax[i-1][j], localMax[i][j])      ==>    globalMax[j] = max(globalMax[j], localMax[j])

 

For here ,diff = prices[i+1] - prices[i]. max(0, diff) means only when the profit is positive, we add it to globalMax.

 

 1 class Solution {
 2 public:
 3     int maxProfit(int k, vector<int> &prices) {
 4         int len = prices.size(), result = 0;
 5         if (len < 2) return 0;
 6         if (len <= k) {
 7             for (int i = 0; i < len-1; i++) {
 8                 if (prices[i+1] - prices[i] > 0) {
 9                     result += prices[i+1] - prices[i];
10                 }
11             }
12         } else {
13             vector<int> lMax(k+1, 0), gMax(k+1, 0);
14             for (int i = 0; i < len-1; i++) {
15                 int diff = prices[i+1] - prices[i];
16                 for (int j = k; j >= 1; j--) {
17                     lMax[j] = max(gMax[j-1] + max(0, diff), lMax[j] + diff);
18                     gMax[j] = max(lMax[j], gMax[j]);
19                 }
20             }
21             result = gMax[k];
22         }
23         return result;
24     }
25 };

 

posted on 2015-03-18 07:27  keepshuatishuati  阅读(222)  评论(0编辑  收藏  举报