Problem 309 · LeetCode 309(opens in a new tab)
Best Time to Buy and Sell Stock with Cooldown
MediumArrays
The list prices gives a stock's price for each day: day i costs prices[i]. You may buy and sell as many times as you like, but you can own at most one share at a time: sell before you buy again.
There is one more rule. On the day right after a sale you are not allowed to buy; that day is a cooldown. Return the largest total profit you can make. Making no trades at all, for a profit of 0, is allowed.
Example 1
Input: prices = [2, 5, 1, 1, 4] Output: 6 Why: buy at 2, sell at 5, cool down, buy at 1, sell at 4
2 more examples and the constraints
Example 2
Input: prices = [1, 4, 2, 6] Output: 5 Why: selling at 4 blocks buying at 2, so buy at 1 and sell at 6
Example 3
Input: prices = [9, 7, 3] Output: 0 Why: prices only fall, so never trade
Constraints
- 1 ≤ length of prices ≤ 5,000
- 0 ≤ prices[i] ≤ 1,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try every choiceO(2ⁿ)
- Three states, one passO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 5,000 days | Verdict |
|---|---|---|---|
| Try every choice | O(2ⁿ) | Mention it, then move on | |
| Three states, one pass | O(n) | Best; three numbers |
n = number of days.
Edge cases to test
- One day. You cannot buy and sell on different days, so the answer is 0.
- Falling prices. Never trading gives 0, and no trade can beat it.
- Cooldown in the way. [1, 4, 2, 6]: two trades would give 7 without the rule, but the cooldown forces 5.
- Flat prices. Every price the same: trades break even, the answer is 0.
Common mistakes
- Updating
holdbefore computingsold, so a share is bought and sold on the same day. - Letting
holdbuy fromsoldinstead ofrest, which skips the cooldown. - Returning
holdor including it in the answer: ending with a share is never better.
How to talk through it
- 1Clarify. One share at a time? Does the cooldown come only after a sale, and does it last one day?
- 2Give the brute force. Recurse on (day, holding) with skip, buy and sell; note the repeated subproblems.
- 3Name the states. hold, sold and rest describe every end of day, and each depends only on yesterday.
- 4Code the transitions. Write the three updates and say why they must all read yesterday's values.
- 5Test out loud. Run one day, falling prices, and a case where the cooldown changes the answer.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?