【动态规划】Best Time to Buy and Sell Stock IV
来源:互联网 发布:小学生画图软件ipad 编辑:程序博客网 时间:2024/06/05 07:01
题目:leetcode
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).
我们定义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])
其中局部最优值是比较前一天并少交易一次的全局最优加上大于0的差值,和前一天的局部最优加上差值后相比,两者之中取较大值,而全局最优比较局部最优和前一天的全局最优。
若k值大于等于天数减一,则可以视为交易次数没有限制,可单独讨论。
class Solution {public: int maxProfit(int k, vector<int> &prices) { int size=prices.size(); if(size<=1 && k<=0) return 0; if(k>=size-1) return buxianzhi(prices); vector<vector<int>> local(size,vector<int>(k+1,0)),global(size,vector<int>(k+1,0)); for(int i=1;i<size;i++) { int diff=prices[i]-prices[i-1]; for(int j=1;j<=k;j++) { if(j>i) { local[i][j]=local[i][i]; global[i][j]=global[i][i]; continue; } local[i][j]=max(global[i-1][j-1]+max(diff,0),local[i-1][j]+diff); global[i][j]=max(global[i-1][j],local[i][j]); } } return global[size-1][k]; } int buxianzhi(vector<int> &prices) { int res=0,size=prices.size(); for(int i=1;i<size;i++) { if(prices[i]>prices[i-1]) res+=prices[i]-prices[i-1]; } return res; }};
0 0
- 【动态规划】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 动态规划dp解法(C++)
- LeetCode 188 Best Time to Buy and Sell Stock IV (动态规划 推荐)
- Best Time to Buy and Sell Stock I II III IV (第四周 动态规划)
- 动态规划-188. Best Time to Buy and Sell Stock IV
- Leetcode(W9):188. Best Time to Buy and Sell Stock IV(动态规划)
- 动态规划-121. Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock IV
- [LeetCode] Best Time to Buy and Sell Stock IV
- Best Time to Buy and Sell Stock IV
- 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(188) Best Time to Buy and Sell Stock IV
- 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(未完成)
- 讲故事,学(Java)设计模式—桥接模式
- struts2基本知识总结1
- java开发过程中遇到的问题
- 【二进制求反序】LeetCode初试验_Reverse Bits
- 使用taglist插件
- 【动态规划】Best Time to Buy and Sell Stock IV
- Maven3路程(三)用Maven创建第一个web项目(1)
- Oracle忘记用户名、密码
- 【c语言】判断一个字符串是不是回文字符串
- Redis的发布/订阅(pub/sub)
- jQuery中filter()和find()的区别
- 提取元素的轮廓及形状描述子
- Linux环境编程之信号处理(三、利用alarm()和pause()函数实现sleep()函数)
- 以mvn命令运行main函数