码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – Best Time to Buy and Sell Stock iv

时间:2015-03-18 07:49:13      阅读:399      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

LeetCode – Refresh – Best Time to Buy and Sell Stock iv

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4346166.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!