# 309. 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:**

```
Input: [1,2,3,0,2]
Output: 3 
Explanation: transactions = [buy, sell, cooldown, buy, sell]
```

#### 解题要点：

大神用state machine的方式，表达出来dp的解法。

![](https://375347639-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LaRt7GO3PReMl3lhW_c%2F-LsTqxDy2ju-gdCNhra1%2F-LsTrIAFiUmh8v63N7ex%2Fimage.png?alt=media\&token=ea964997-d8fc-4b0a-9cf7-4e3d3d9de09b)

```python
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) == 0: return 0
        s0 = [0] * len(prices)
        s1 = [0] * len(prices)
        s2 = [0] * len(prices)
        s0[0] = 0
        s1[0] = -prices[0]
        s2[0] = -sys.maxint
        for i in range(1, len(prices)):
            s0[i] = max(s0[i-1], s2[i-1])
            s1[i] = max(s1[i-1], s0[i-1] - prices[i])
            s2[i] = s1[i-1] + prices[i]
        return max(s0[-1], s2[-1])
```
