Python 3D Academyবাংলা

State machines: stocks with a cooldown

🌍 In real life. A trader in Chattogram may buy and sell a commodity as often as they like, but holds at most one lot at a time, and after selling must rest one day before buying again (the money takes a day to clear). Given the price each day, what is the most they can make?

Greedy rules ("sell at every rise") break because of the rest day. A DP whose state is not a position but a situation you are in, holding, just sold, or resting, follows every choice at once. That is a state machine DP (LeetCode 309, and 714 with a fee).

The idea in one sentence: keep, for each day, the best money you could have in each state, holding a lot, having just sold, or resting with no lot, and work out today's three numbers from yesterday's through the moves allowed between states.

Its words:

  • state: the situation at the end of a day: hold, sold (sold today) or rest (no lot, free to buy)
  • transition: a move between states: rest → hold (buy), hold → sold (sell), sold → rest (cool down), and staying put
  • cooldown: the day after a sale, when buying is not allowed

The moves, written as a DP. For today's price p:

  • hold = max(keep holding: hold, buy today from resting: rest - p)
  • sold = sell what you held: hold + p
  • rest = max(keep resting: rest, cool down after yesterday's sale: sold)

All three use yesterday's values, so they are updated together in one line. Watch prices 1, 2, 3, 0, 2:

Why it is correct. At the end of any day you are in exactly one of the three states, and every legal history ending in a state must have come from one of the moves into it. Taking the best over those moves keeps "the best money in each state" true day after day; the answer is the better of the two states with no lot at the end. The cooldown is enforced by the shape of the machine: there is no move from sold straight to hold.

Other rules, other machines. Change the states and moves and the same pattern solves the whole family:

  • unlimited trades, no cooldown: two states, hold and cash
  • a fee per trade (LeetCode 714): cash = max(cash, hold + p - fee)
  • at most k trades (LeetCode 188): one hold and one cash per number of trades used

What it costs, by counting. A constant number of states and moves per day: O(n) time and O(1) memory. The plain recursion "buy, sell or wait on each day" is O(3ⁿ).

def max_profit_cooldown(prices):
    hold, sold, rest = float("-inf"), 0, 0  # best money in each state, so far
    for p in prices:
        hold, sold, rest = (
            max(hold, rest - p),            # keep holding, or buy today (from rest)
            hold + p,                       # sell today
            max(rest, sold),                # stay free, or yesterday's sale cools down
        )
    return max(sold, rest)


def max_profit_fee(prices, fee):
    hold, cash = float("-inf"), 0
    for p in prices:
        hold, cash = max(hold, cash - p), max(cash, hold + p - fee)
    return cash


print(max_profit_cooldown([1, 2, 3, 0, 2]), max_profit_cooldown([5, 4, 3]))
print(max_profit_fee([1, 3, 2, 8, 4, 9], 2))
With a fee of 2, it is better to hold from 1 to 8 than to sell at 3 and buy again at 2: two trades pay two fees.

Mistakes and edge cases.

  • Updating the states one after another. hold = ... then sold = hold + p uses today's new hold, so you can buy and sell on the same day and break the cooldown. Update all states together, from yesterday's values.
  • Starting hold at 0. That pretends you already own a lot for free; start it at -inf.
  • Buying from sold. hold = max(hold, sold - p) skips the rest day.
  • Returning hold. Ending with an unsold lot is never better; answer with the states that have no lot.
  • No prices, or one. No trade can make money: the answer is 0.

Quiz

  1. What does this print?

    def max_profit_cooldown(prices):
        hold, sold, rest = float("-inf"), 0, 0  # best money in each state, so far
        for p in prices:
            hold, sold, rest = (
                max(hold, rest - p),            # keep holding, or buy today (from rest)
                hold + p,                       # sell today
                max(rest, sold),                # stay free, or yesterday's sale cools down
            )
        return max(sold, rest)
    
    
    print(max_profit_cooldown([1, 4, 2]), max_profit_cooldown([2, 1, 4]))
  2. Which move is missing from the cooldown machine on purpose?

    • sold → hold: buying on the day right after a sale
    • rest → hold
    • hold → sold
  3. Why does hold start at float("-inf") instead of 0?

    • Before any purchase, holding a lot is impossible; 0 would mean owning one for free
    • To make the profit negative
    • Python needs it for max
  4. For prices [1, 2, 3, 0, 2] the answer should be 3, but this gives 4: it sells and buys again on the same day. Which line is wrong?

    def max_profit_cooldown(prices):
        hold, sold, rest = float("-inf"), 0, 0
        for p in prices:
            hold = max(hold, rest - p)
            sold = hold + p
            rest = max(rest, sold)
        return max(sold, rest)

Coding tasks

  1. Write max_profit_cooldown(prices): as many trades as you like, one lot at a time, and after a sale you must wait one day before buying again.

  2. Write max_profit_fee(prices, fee): as many trades as you like, one lot at a time, no cooldown, but every sale costs fee.