> For the complete documentation index, see [llms.txt](https://jaywin.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jaywin.gitbook.io/leetcode/solutions/0309-best-time-to-buy-and-sell-stock-with-cooldown.md).

# 0309. Best Time to Buy and Sell Stock with Cooldown

<https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown>

## Description

You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.

Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:

* After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).

**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

**Example 1:**

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

**Example 2:**

```
**Input:** prices = [1]
**Output:** 0
```

**Constraints:**

* `1 <= prices.length <= 5000`
* `0 <= prices[i] <= 1000`

## ac

```java
class Solution {
    public int maxProfit(int[] prices) {
        // edge cases
        if (prices == null || prices.length <= 1) return 0;

        int holdPrev = Integer.MIN_VALUE, emptyPrev = 0, cooldownPrev = 0;
        for (int i = 0; i < prices.length; i++) {
            int empty = Math.max(emptyPrev, cooldownPrev);
            int hold = Math.max(holdPrev, emptyPrev-prices[i]);
            int cooldown = holdPrev + prices[i];
            holdPrev = hold;
            emptyPrev = empty;
            cooldownPrev = cooldown;
            // make sure the variables are from last step, not updated in current step, hold, empty, cooldown
        }

        return Math.max(emptyPrev, cooldownPrev);
    }
}
```
