0%

### leetcode Best Time to Buy and Sell Stock with Cooldown

Say you have an array for which the _i_th 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 = 3

• 你每次只能买一支而且在再次买入之前必须出售之前手头上的股票（就是手头上最多有一支股票）
• 每次出售需要休息一天才能再次买入

### Idea

DP，we can create two array, buy and sell.

and sell[i] means we sell or not sell a stock at day i to  maximize profits.

so, we have two equations :

• buy[i] = max(buy[i-1] , sell[i-2] - prices[i])  // So we should use sell[i-2] means we cooldown one day.
• sell[i] = max(sell[i-1], buy[i-1] + prices[i])

finally, it is obvious that sell[n-1] >= buy[n-1],so we return sell[n-1]

have more parctice in :    leetcode Best Time to Buy and Sell Stock I ~ IV