309. Best Time to Buy and Sell Stock with Cooldown

Description：
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)
Difficulty：Medium
Example:

Input: [1,2,3,0,2]
Output: 3


方法1：动态规划

• Time complexity : O ( n ) O\left ( n \right )
• Space complexity : O ( n ) O\left ( n \right )
思路：
buy[i] = max(sell[i-2]-price, buy[i-1])
sell[i] = max(buy[i-1]+price, sell[i-1])
class Solution {
public:
int maxProfit(vector<int> &prices) {
int max_profit = 0, n = prices.size();
if(n < 2) return 0;
sell[1] = max(buy[0] + prices[1], sell[0]);
max_profit = max(max_profit, sell[1]);
for(int i = 2; i < n; i++){
sell[i] = max(buy[i-1] + prices[i], sell[i-1]);
max_profit = max(max_profit, sell[i]);
}
return max_profit;
}
};


方法2：动态规划， 空间优化

• Time complexity : O ( n ) O\left ( n \right )
• Space complexity : O ( 1 ) O\left ( 1 \right )
思路：
根据dp公式我们可以看出，我们只需要i, i-1, i-2三个时刻的值即可，故省去数组空间
buy[i] = max(sell[i-2]-price, buy[i-1])
sell[i] = max(buy[i-1]+price, sell[i-1])
class Solution {
public:
int maxProfit(vector<int> &prices) {
for (int price : prices) {
prev_sell = sell;//注意区别！！！
sell = max(prev_buy + price, sell);
}
return sell;
}
};

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

Freeman_zxp

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
10-26