# 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 = max(buy + prices, sell);
max_profit = max(max_profit, sell);
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;
}
};

09-03 1158 06-25 72
04-09 906
01-23 175
01-18 246
08-26 179
03-04 70
12-06 212
02-20 133