Best Time to Buy and Sell Stock

EasyOne passLeetCode 121 ↗World 2-1
0:00 / 0:00

Buy one day, sell on a later day, for the biggest profit. Walk the prices once, remembering the cheapest day so far.

▼

The problem

LeetCode 121 (Easy). Given a list of prices, one per day, buy on one day and sell on a later day for the biggest profit; if no trade makes money, the answer is 0.

Example: [9, 4, 8, 2, 5, 7, 3] → 5 (buy at 2 on day 4, sell at 7 on day 6).

TRY IT ON LEETCODE ▶

The solution

def max_profit(prices):
    low, best = prices[0], 0
    for today in prices:
        low = min(low, today)
        best = max(best, today - low)
    return best

Transcript

Best Time to Buy and Sell Stock. You get a stock's price for each day. Buy one day, sell on a later day. What's the biggest profit? If prices only fall, no trade makes money, so the answer is zero.

Take nine, four, eight, two, five, seven, three. The tempting move: buy at the lowest price, sell at the highest. But the highest, nine, comes on day one, before every low. You can't sell before you buy. The real best trade is buy at two, sell at seven, a profit of five.

The safe way tries every buy day with every later sell day. Seven days give twenty-one pairs. But the count grows like n squared. Ten thousand days means almost fifty million pairs. Too slow.

Here's the trick. Imagine selling on one day. The best day to have bought is simply the cheapest day before it. So you only need one number: the lowest price so far. Today minus that low is the best sale today. Keep the biggest.

Let's walk it. Day one, nine is the low. Four is lower, so the buy flag moves down. Eight minus four is four: our first best. Two is a new low, and the flag drops again. The best stays four; a new low doesn't erase it. Five minus two is three, not better. Seven minus two is five: a new best. Three minus two is one. The answer is five.

In code, low starts at the first price, and best at zero. Loop over the prices. Low becomes the smaller of low and today. Best becomes the bigger of best and today minus low. Then return best. Updating low first is safe: on a new low, today minus low is just zero.

One pass over the list, so the time is O of n. Just two numbers, low and best, so the space is constant. Ten thousand days take ten thousand steps, not fifty million.

Remember the low, check today, keep the best. That's Best Time to Buy and Sell Stock.