LeetCode:Best time to Buy and Sell Stock IV
来源:互联网 发布:美女网络名字大全 编辑:程序博客网 时间:2024/06/10 06:28
题目:
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).
思路:
这道题与上次的Best time to Buy and Sell Stock III 的不同之处在于这次的最大交易次数不再是2,而是k,所有不能再用我前面两篇博客所用的方法了。
这次仍然使用动态规划来解题,用的是“局部最优和全局最优法”。我们需要维护两个变量,local[i][j]为在到达第i天时最多进行j次交易且第j次交易在第i天卖出的最大利润,此为局部最优;global[i][j]为在到达第i天时最多可进行j次交易的最大利润,此为全局最优。
显然,全局的递推式为global[i][j]=max(local[i][j], global[i-1][j]);局部的递推式为local[i][j]=max(global[i-1][j-1]+max(diff,0), local[i-1][j]+diff),第一个量全局到达i-1天进行j-1次交易,那么第j次的交易可以是第i-1天买进,第i天卖出(利润为diff),也可以是第i天买进且卖出(利润为0),所以两者之中取最大;第二个量则是取local第i-1天进行j次交易,因为要第i天进行第j次交易,所以只需要把原来是第i-1天卖出的交易改成第i天才卖出,即加上差价diff。
本题有一种特殊情况,就是如果k的值远大于prices的天数,用上面的方法效率很低,需要改进。这种情况相当于交易次数不限,那么只要后一天与前一天的差价大于0,就可以进行交易了。
代码:
class Solution {public: int maxProfit(int k, vector<int>& prices) { if (prices.size() == 0) return 0; if (prices.size() <= k) return maxmaxProfit(prices); int local[k+1] = {0}; int global[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--) { local[j] = max(global[j-1] + max(diff, 0), local[j]+diff); global[j] = max(global[j], local[j]); } } return global[k]; } int maxmaxProfit(vector<int>& prices) { int profit = 0; for (int i = 1; i < prices.size(); i++) { if (prices[i] - prices[i-1] > 0) { profit += prices[i] - prices[i-1]; } } return profit; }};
时间复杂度:O(n*k)
参考博客:
http://blog.csdn.net/linhuanmars/article/details/23236995
http://www.cnblogs.com/grandyang/p/4295761.html
- [LeetCode] Best Time to Buy and Sell Stock IV
- leetcode: Best Time to Buy and Sell Stock IV
- LeetCode(188) Best Time to Buy and Sell Stock IV
- Best Time to Buy and Sell Stock IV -- leetcode
- Best Time to Buy and Sell Stock IV--LeetCode
- LeetCode : Best Time to Buy and Sell Stock III & IV
- Best Time to Buy and Sell Stock IV Leetcode Java
- LeetCode: Best Time to Buy and Sell Stock IV
- leetcode 188---Best Time to Buy and Sell Stock IV
- LeetCode Best Time to Buy and Sell Stock IV
- [leetcode] 188.Best Time to Buy and Sell Stock IV
- LeetCode - Best Time to Buy and Sell Stock IV
- [LeetCode][Java] Best Time to Buy and Sell Stock IV
- 【leetcode】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
- Leetcode: Best Time to Buy and Sell Stock IV
- LeetCode Best Time to Buy and Sell Stock IV
- mysql5.6 修改配置my.cnf,进行性能优化
- [ArcGIS] 空间分析(九)3D视线分析(构造视线、通视性) ArcScene简单使用
- SQL 大数据查询如何进行优化?
- 一个记录手机log的多线程类
- zookeeper 使用场景
- LeetCode:Best time to Buy and Sell Stock IV
- 【技术分享】node.js + postgres 从注入到Getshell
- MySQL的基本操作
- Merge into 详细介绍
- 微信小程序支付功能--优化
- RocketMQ源码简析
- 感知机的对偶形式
- oracle 多个实例互相切换实例
- Python学习笔记(2)- 字符串和数字