188. Best Time to Buy and Sell Stock IV
来源:互联网 发布:charcodeat js 编辑:程序博客网 时间:2024/06/03 05:54
这道是买股票的最佳时间系列问题中最难最复杂的一道,之前有一个是最多交易两次,和这个题的思路一样。还是需要用动态规划Dynamic Programming来解,而这里我们需要两个递推公式来分别更新两个变量local和global。我们定义local[i][j]为在到达第i天时最多可进行j次交易并且最后一次交易在最后一天卖出的最大利润,此为局部最优。然后我们定义global[i][j]为在到达第i天时最多可进行j次交易的最大利润,此为全局最优。它们的递推式为:
local[i][j] = max(global[i - 1][j - 1] + max(diff, 0), local[i - 1][j] + diff)
global[i][j] = max(local[i][j], global[i - 1][j])
由于只用到了i-1,所以可以用两个一维数组来替代,即:
local[i] = max(global[i-1] + max(diff, 0), local[i] + diff)
global[i] = max(global[i], local[i])
其中局部最优值是比较前一天并少交易一次的全局最优加上大于0的差值,和前一天的局部最优加上差值中取较大值,而全局最优比较局部最优和前一天的全局最优。
但这道题还有个坑,就是如果k的值远大于prices的天数,比如k是好几百万,而prices的天数就为若干天的话,上面的DP解法就非常的没有效率,应该直接用Best Time to Buy and Sell Stock II 买股票的最佳时间之二的方法来求解,所以实际上这道题是之前的二和三的综合体,代码如下:
class Solution {public: int maxProfit(int k, vector<int>& prices) { if(prices.empty()) return 0; if(k >= prices.size()) return solveMaxProfit(prices); int g[k + 1] = {0}; int l[k + 1] = {0}; for(int i = 0; i < prices.size()-1; ++i){ int diff = prices[i + 1] - prices[i]; for(int j = k; j >= 1; --j){ l[j] = max(g[j - 1] + max(diff, 0), l[j] + diff); g[j] = max(g[j], l[j]); } } return g[k]; } int solveMaxProfit(vector<int>& prices){ int res = 0; for(int i = 1; i < prices.size(); ++i){ if(prices[i] - prices[i - 1] > 0){ res += prices[i] - prices[i - 1]; } } return res; }};
- [leetcode] 188.Best Time to Buy and Sell Stock IV
- [leetcode] 188.Best Time to Buy and Sell Stock IV
- [leetcode] 188. Best Time to Buy and Sell Stock IV
- 188. Best Time to Buy and Sell Stock IV
- 188. Best Time to Buy and Sell Stock IV
- [LeetCode] 188. Best Time to Buy and Sell Stock IV
- Leetcode 188. Best Time to Buy and Sell Stock IV
- 188. Best Time to Buy and Sell Stock IV
- 【leetcode】188. Best Time to Buy and Sell Stock IV
- LeetCode 188. Best Time to Buy and Sell Stock IV
- 188. Best Time to Buy and Sell Stock IV
- 188. Best Time to Buy and Sell Stock IV
- 188. Best Time to Buy and Sell Stock IV
- 188. Best Time to Buy and Sell Stock IV
- 188. Best Time to Buy and Sell Stock IV
- Leetcode 188. Best Time to Buy and Sell Stock IV
- Leetcode 188. Best Time to Buy and Sell Stock IV
- 188. Best Time to Buy and Sell Stock IV
- java面试总结-4 spring
- 做为一名教C程的老师
- 使用Java产生Int类型的随机数
- 【笔记】冒泡排序
- selenium+python模拟登陆163邮箱
- 188. Best Time to Buy and Sell Stock IV
- iOS Xcode~代码块前面标记的 M,C,T等字母含义
- 接口详解,戳进来....
- Android安卓——Activity组件(1)
- 自定义View+接口回调 圆进度条+二维码+梯形布局
- 2017ACMICPC亚洲区青岛站:I:The Squared Mosquito Coil【模拟题】
- Win32Demo
- 设计模式笔记(一)设计六大原则之一--单一职责原则
- 处理图片流