[leetcode]309. Best Time to Buy and Sell Stock with Cooldown
来源:互联网 发布:如何用c语言编写程序 编辑:程序博客网 时间:2024/06/11 20:39
题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
- You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
- After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
prices = [1, 2, 3, 0, 2]maxProfit = 3transactions = [buy, sell, cooldown, buy, sell]
买入状态分两种情况:一、和前一天的状态一样;二、前两天是卖出,前一天是冷却期,今天买入。
卖出状态分两种情况:一、和前一天的状态一样;二、前一天是买入状态,今天卖出。
状态转移方程:buyUp[i]=max(buyUp[i-1],sellUp[i-2]-prices[i])
sellUp[i]=max(sellUp[i-1],buyUp[i-1]+prices[i])
最后一天肯定是卖出。
class Solution{public: int maxProfit(vector<int>& prices)//profit=max() { if (prices.size()==0) return 0; vector<int> sellUp(prices.size(),0); vector<int> buyUp(prices.size(),0); buyUp[0]=-prices[0]; sellUp[0]=0; for(int i=1;i<prices.size();i++) { if(i<2) buyUp[i]=max(buyUp[i-1],-prices[i]); else buyUp[i]=max(buyUp[i-1],sellUp[i-2]-prices[i]); sellUp[i]=max(sellUp[i-1],buyUp[i-1]+prices[i]); } return sellUp[prices.size()-1]; }};
0 0
- 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
- 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
- Sping boot系列--redis之2 -- RedisKeyValueTemplate处理Model对象
- hibernate单元测试中表不存在的错误解决方法
- 蓝桥杯算法提高 打水问题
- Git学习笔记
- 委托(五):多播委托
- [leetcode]309. Best Time to Buy and Sell Stock with Cooldown
- HDU1215:七夕节(简单数论)
- 博弈论一般性解法总结
- LeetCode-Q3-Longest Substring Without Repeating Characters
- eclipse UML 学习 Rose
- (转)23种设计模式(4):建造者模式(实例代码并不怎么好)
- 交换与路由知识点总结(四)
- UVa 10118 Free Candies (记忆化搜索+状态压缩)
- Json安全