【LeetCode题解】309. Best Time to Buy and Sell Stock with Cooldown
来源:互联网 发布:数据建模知乎理论物理 编辑:程序博客网 时间:2024/06/11 22:37
此题在之前121题的基础上做了细微调整,首先可以有多次买入或卖出的事件发生,且在卖出股票的下一天不能进行股票交易活动
解题思路:
需要创建两个辅助数组sell和buy,sell[i]第i天不持有股票的最大利润,buy[i]表示第i天持有股票的最大利润。
一天的交易状态就是否持有股票来说,只包含持有状态和不持有状态两种
1、对于持有状态,今日可能没有进行买入操作所以跟昨天持股状态一样;也可能今天买入昨天是冷却期,所以利润为前天卖出股票的利润减去今天买入股票的价格。两者取最大
2、对于非持有状态,可能今天没有卖出所以跟昨天非持有状态一样;也可能昨天持有股票今天卖出,所以利润是昨天持有股票的利润加上今天股票价格。两者取最大
状态方程为:
sell[i] = max{sell[i-1] ,buy[i-1]+prices[i]}
buy[i] = max{buy[i-1],sell[i-2]-prices[i]}
代码:
class Solution {public: int maxProfit(vector<int>& prices) { int n = prices.size(); if(n<2) return 0; vector<int> sell(n,0); vector<int> buy(n,0); buy[0] = -prices[0]; for(int i=1; i<n; i++){ sell[i] = max(sell[i-1],buy[i-1]+prices[i]); buy[i] = max(buy[i-1],sell[i-2]-prices[i]); } return sell[n-1]; }};
阅读全文
0 0
- 【LeetCode题解】309. Best Time to Buy and Sell Stock with Cooldown
- LeetCode题解:309. Best Time to Buy and Sell Stock with Cooldown
- leetcode Best Time to Buy and Sell Stock with Cooldown
- LeetCode Best Time to Buy and Sell Stock with Cooldown
- Leetcode: Best Time to Buy and Sell Stock with Cooldown
- [LeetCode]Best Time to Buy and Sell Stock with Cooldown
- Leetcode Best Time to Buy and Sell Stock with Cooldown
- leetcode - Best Time to Buy and Sell Stock with Cooldown
- LeetCode:Best Time to Buy and Sell Stock with Cooldown
- leetcode Best Time to Buy and Sell Stock with Cooldown
- Leetcode Best Time to Buy and Sell Stock with Cooldown
- LeetCode:Best Time to Buy and Sell Stock with Cooldown
- LeetCode--Best Time to Buy and Sell Stock with Cooldown
- LeetCode题解:Best Time to Buy and Sell Stock with Cooldown
- 309.Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- easyUi分页以及条件查询
- Java.NET.UnknownHostException:Z2ze3ewkwzrm8i64hkqf9
- [torch]optim.sgd学习参数
- 配置spring拦截器需要注意的地方
- System.arraycopy的用法
- 【LeetCode题解】309. Best Time to Buy and Sell Stock with Cooldown
- 【LeetCode】435. Non-overlapping Intervals
- phonegap环境准备
- ios自定义键盘
- MongoDB基础配置及权限配置
- VM12安装centos
- 控件问题
- bzoj 3140: [Hnoi2013]消毒 dfs+网络流
- C++静态库与动态库区别