Best Time to Buy and Sell Stock with Cooldown

MediumDynamic programmingLeetCode 309 ↗World 5-5
0:00 / 0:00

Max profit when every sale forces a one-day rest: track three states each day (holding, just sold, resting) and step them forward together.

▼

The problem

LeetCode 309 (Medium). prices[i] is the price on day i. Complete as many buy/sell transactions as you like, holding at most one share at a time, but after selling you must wait one day (cooldown) before buying again. Return the maximum profit.

Example (LeetCode's): [1, 2, 3, 0, 2] → 3: buy, sell, cooldown, buy, sell = (2 − 1) + (2 − 0).

TRY IT ON LEETCODE ▶

The solution

def max_profit(prices):
    hold, sold, rest = -prices[0], 0, 0
    for p in prices[1:]:
        hold, sold, rest = (max(hold, rest - p),
                            hold + p,
                            max(rest, sold))
    return max(sold, rest)

Transcript

Best Time to Buy and Sell Stock with Cooldown. Each day, the stock has a price. Trade as often as you like, but hold only one share at a time. The catch: after you sell, you must rest a day before buying again. What's the most profit?

Take prices one, two, three, zero, two. The best plan: buy at one, sell at two, rest, buy at zero, sell at two. One plus two: a profit of three. Selling at three looks better, but then the cooldown lands on the cheapest day, and you end with two.

The naive way tries every plan. Each day you act or wait, so the plans nearly double every day. Five days give twenty-one paths; thirty days, about twenty-seven million.

Instead, track where you could be each evening: one of three states. Hold: you own a share. Sold: you sold today, so tomorrow is a cooldown. Rest: no share, free to buy. Keep the best profit for each. Every day follows three rules. Hold keeps holding, or buys from rest, paying the price. Sold comes only from hold, earning the price. Rest keeps resting, or comes from yesterday's sold.

Let's walk the example. Day one: buy, so hold is minus one. Day two: selling gives one. Day three: selling at three gives two, and rest picks up one. Day four, price zero: rest buys, so hold climbs to one. Day five: selling at two gives three. The answer is the larger of sold and rest: three.

In code, hold starts at minus the first price, and sold and rest at zero. For each later price, update all three at once from yesterday's values. Return the larger of sold and rest.

Three updates a day, in one pass: order n time. Just three numbers: constant space. Thirty days take ninety updates, not twenty-seven million paths.

Three states, three rules, one day at a time. That's Best Time to Buy and Sell Stock with Cooldown.