The Runtime Theory
easyleetcode#array#sliding-window

Best Time to Buy and Sell Stock

Find the maximum profit from one buy and one sell by tracking the minimum price seen so far in a single pass over the price array.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

in[7,1,5,3,6,4]

out5

in[7,6,4,3,1]

out0

in[1,2]

out1

The machine gets one pass over an array of daily prices and must find the single buy/sell pair with the maximum profit — buy before sell, one transaction only. Brute force pairs every buy with every later sell: O(n²). The insight: at any moment, the best possible sale today is price - min_price_so_far. Track the minimum as you go; you never need to look back.

python
def max_profit(prices):
    min_price = float("inf")
    profit = 0
    for price in prices:
        if price < min_price:
            min_price = price
        elif price - min_price > profit:
            profit = price - min_price
    return profit

Steps: (1) keep a running minimum, (2) for each price compute the profit if sold today, (3) keep the largest profit seen.

Time is O(n), one pass. Space is O(1) — just two integers.

Trickiest edge case: a monotonically falling array like [7,6,4,3,1]. The best transaction is no transaction, so profit stays 0 — the answer is never negative, and there is no forced trade. A single-day array returns 0 for the same reason.

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.