123. Best Time to Buy and Sell Stock III(动规的好题)
来源:互联网 发布:mac版cad字体乱码 编辑:程序博客网 时间:2024/06/05 08:41
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 two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
class Solution {public: int maxProfit(vector<int>& prices) {}};
解答:
这个题目可以直接推广到k transactions的情形:
用f[i][j]表示最多i笔交易下在prices[j]处(不包括prices[j])能取得的最大利润,那么f[i][j]=max(f[i][j-1],p[j]-p[k]+f[i-1][k]),k∈[0,j]
也就是说,在第j天,要么卖掉要么不卖(卖了才会赚钱),如果不卖,f[i][j]和f[i][j-1]一样,如果卖,那么前面一定买过(也就是损失过钱),假设损失的是p[k],这样,在第j天卖掉东西的情况下赚取的利润就是p[j]-p[k]+f[i-1][k],其中f[i-1][k]表示做最多i-1笔交易时在p[k]处取得的利润。
这个式子可以改写成:f[i][j]=max(f[i][j-1],max(f[i-1][k]-p[k])+p[j]),k∈[0,j]
改写的理由是:我们需要对p[j]-p[k]+f[i-1][k]取最大值,p[j]是定值,那么只有让f[i-1][k]-p[k]取最大。
AC代码:
class Solution {public: int maxProfit(vector<int>& prices) { int tmp,len=prices.size(); int k=2; vector<vector<int>>dp(k+1,vector<int>(len,0)); if(len<=1)return 0; for(int i=1;i<=k;i++){ tmp=dp[i-1][0]-prices[0]; for(int j=1;j<len;j++){ dp[i][j]=max(dp[i][j-1],prices[j]+tmp); tmp=max(tmp,dp[i-1][j]-prices[j]); } } return dp[k][len-1]; }};
- 123. Best Time to Buy and Sell Stock III(动规的好题)
- LeetCode 123. Best Time to Buy and Sell Stock III
- 123.Best Time to Buy and Sell Stock III
- [Leetcode]123.Best Time to Buy and Sell Stock III
- [Leetcode] 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- [leetcode] 123.Best Time to Buy and Sell Stock III
- 【leetcode】123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- [leetcode] 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- leetcode 123. Best Time to Buy and Sell Stock III
- leetcode 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- [LeetCode] 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- webstorm添加vue模板支持
- [cs231n之第二课]Image Classification
- 纪实:即时通讯.net signalr初探索
- stm32学习笔记(六)窗口看门狗
- ZooKeeper 会话超时
- 123. Best Time to Buy and Sell Stock III(动规的好题)
- OSG 让模型变成你想要的颜色 (贴纹理)
- 与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误。
- Spring的另一种属性注入(依赖注入)
- 谈谈学习方法。
- Begin ... End
- Android studio中的aidl
- 商城购物车加减控件的简单封装
- Spring总结笔记(三)