Best Time to Buy and Sell Stock with Cooldown
MediumNeetCode 150 2-D Dynamic ProgrammingGeicoProblem
prices[i] is the price of a stock on day i. You may buy and sell as many times as
you like, with two rules:
- You can own at most one share at a time, so you must sell before buying again.
- The day after you sell is a cooldown. You cannot buy on that day.
Return the largest total profit you can make.
Constraints
- 1 ≤ prices.length ≤ 5000
- 0 ≤ prices[i] ≤ 1000
Examples: pick one to animate
Solutions
TimeO(n)
SpaceO(n)
Time: Each of the n days fills three cells, and each cell reads at most two cells from the day before.
Space: Three arrays of length n: 3n cells.
Track three states per day. hold: own a share. sold: sold today.
rest: own nothing and free to buy. Buying is only allowed from rest, which
encodes the cooldown.