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

Best Time to Buy and Sell Stock IV****

时间:2015-08-21 08:16:21      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most k transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

 

Analyse: Assume global[i][j] represents the maximum profit at day i with j transactions, local [i][j] is the maximum profit at day i  with j transactions at the last transaction occurred on day i. Then we have: global[i][j] = max(local[i][j], global[i - 1][j]) (the left one is doing the transaction at day i while the right one is not doing the transaction at day i), local[i][j] = max(local[i - 1][j] + diff, global[i - 1][j - 1] + max(0, diff)). (we have to do the j-th transaction on day i, so if we already did j transactions at day i - 1 and did the last transaction on the (i - 1)th day, or we did j - 1 transactions by the (i - 1)th day, then we choose the larger one. 

Runtime: 8ms.

 1 class Solution {
 2 public:
 3     int maxProfit(int k, vector<int>& prices) {
 4         if(prices.size() <= 1 || k == 0) return 0;
 5                 
 6         int result = 0;
 7         if(k >= prices.size()){//cannot do k transactions, then do all operations which can earn money
 8             for(int i = 1; i < prices.size(); i++){
 9                 if(prices[i] > prices[i - 1])
10                     result += prices[i] - prices[i - 1];
11             }
12             return result;
13         }
14        
15         const int n = k + 1;
16         int l[n] = {0}, g[n] = {0};
17         
18         for(int i = 0; i < prices.size() - 1; i++){
19             int diff = prices[i + 1] - prices[i];
20             for(int j = k; j >= 1; j--){
21                 l[j] = max(g[j - 1] + max(0, diff), l[j] + diff);
22                 g[j] = max(l[j], g[j]);
23             }
24         }
25         return g[k];
26     }
27 };

 

Best Time to Buy and Sell Stock IV****

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4746654.html

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