medium2-D Dynamic ProgrammingAmazon
Cooldown Trader
A day trader must wait one day after any sale before buying again. Compute the maximum lifetime profit.
Given stock prices by day, find the max profit with as many buy/sell transactions as desired, but you cannot buy on the day immediately after selling.
Choose approach
hold
-1
?
?
?
?
sold
-∞
day
?
?
?
?
rest
0
?
?
?
?
1/6
Narrationstep 1 of 6
Day 0 price 1: hold=-1, sold=-∞, rest=0.
Variables
day=0
price=1
hold=-1
sold=-Infinity
rest=0
How to think about it
- State machine: hold -> sold -> rest -> hold.
- Cooldown means you can only buy from rest state.
Edge cases to catch in interview
- Monotonically decreasing -> 0.
- Single price -> 0.
Examples
Example 1
0{"prices":[1]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed