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

[LeetCode]Best Time to Buy and Sell Stock IV

时间:2015-09-04 21:14:31      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

Best Time to Buy and Sell Stock IV

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.

 

这题难度明显增大。是Best Time to Buy and Sell Stock IIBest Time to Buy and Sell Stock III两道题的结合。

参考博文,主要是两个递推公式。

1 local[j] = max(local[j] + diff, global[j - 1] + max(diff, 0));
2 global[j] = max(global[j], local[j]);
 1 class Solution {
 2 public:
 3     int maxProfit(int k, vector<int>& prices) {
 4         int result;
 5         int total_times=0;
 6         int profit_max = 0;
 7         for(int i=1;i<prices.size();i++)
 8         {
 9             int diff = prices[i]-prices[i-1];
10             if(diff>0)
11             {
12                 profit_max +=diff;
13                 if(((i<prices.size()-1)&&(prices[i+1]-prices[i]<=0))||(i==prices.size()-1))
14                 {
15                     total_times++;
16                 }
17             }
18         }
19         if(k>=total_times) return profit_max;
20         vector<int> local(k + 1, 0);
21         vector<int> global(k + 1, 0);
22         for(int i = 1; i < prices.size(); i++) 
23         {
24             int diff = prices[i] - prices[i - 1];
25             for(int j = k; j >= 1; j--) {
26                 local[j] = max(local[j] + diff, global[j - 1] + max(diff, 0));
27                 global[j] = max(global[j], local[j]);
28             }
29         }
30         return global[k];
31     }
32 };

 

[LeetCode]Best Time to Buy and Sell Stock IV

标签:

原文地址:http://www.cnblogs.com/Sean-le/p/4782281.html

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