# 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);
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jaywin.gitbook.io/leetcode/solutions/0309-best-time-to-buy-and-sell-stock-with-cooldown.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
