CodeArchon

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.

1def maxProfit(prices):
2 hold, sold, rest = float('-inf'), 0, 0
3 for p in prices:
4 prevSold = sold
5 sold = hold + p
6 hold = max(hold, rest - p)
7 rest = max(rest, prevSold)
8 return max(sold, rest)
Variables
day=0
price=1
hold=-1
sold=-Infinity
rest=0

How to think about it

  1. State machine: hold -> sold -> rest -> hold.
  2. Cooldown means you can only buy from rest state.

Edge cases to catch in interview

  • Monotonically decreasing -> 0.
  • Single price -> 0.

Examples

Example 10
{"prices":[1]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed