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

[LeetCode] Best Time to Buy and Sell Stock IV

时间:2015-08-04 18:38:05      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

An extension of Best Time to Buy and Sell Stock III. The idea is still to use dynamic programming (see here for detailed introduction). However, in this problem, some trick (the quickProfit function below) is required to pass the TLE.

The code is rewritten below.

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

 

[LeetCode] Best Time to Buy and Sell Stock IV

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4702587.html

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