Skip to content

Best Time to Buy and Sell Stock

EasyLeetCode #121Time O(n)Space O(1)

You get a list where prices[i] is a stock’s price on day i. Pick one day to buy and a later day to sell. Return the largest profit possible, or 0 if every trade loses money.

prices = [7, 1, 5, 3, 6, 4] -> 5 (buy at 1, sell at 6)

Brute force tries every buy/sell pair, which is O(n²). The waste: for a given sell day, the best buy day is simply the cheapest price before it. You don’t need to look back; you can carry that number forward.

Walk the array once. Keep lowest, the minimum price seen so far. On each day, the best profit if you sell today is price - lowest. Keep the maximum of those. This is a sliding window where left jumps straight to any new low and right is today.

Show solutionHide solution
def max_profit(prices: list[int]) -> int:
lowest = float("inf") # cheapest price seen so far
best = 0
for price in prices:
lowest = min(lowest, price)
best = max(best, price - lowest) # sell today, bought at the lowest
return best
  • Time: O(n) — a single pass with O(1) work per day.
  • Space: O(1) — two numbers, no matter how long the list is.
  • Update the minimum before computing profit. Doing it in this order makes a day that is a new low give profit 0, which is safe. It also avoids a negative profit.
  • Start best at 0, not at negative infinity. The problem allows “no trade”, so the answer is never negative.
  • Don’t take max(prices) - min(prices). The low must come before the high. In [2, 4, 1] the answer is 2, not 3.

Best Time to Buy and Sell Stock II (LeetCode 122)

Section titled “Best Time to Buy and Sell Stock II (LeetCode 122)”

You may buy and sell as many times as you like (one share held at a time). The trick: greedy. Add every positive day-to-day difference prices[i] - prices[i-1]. Each rise is a trade you could have captured.

Best Time to Buy and Sell Stock with Cooldown (LeetCode 309)

Section titled “Best Time to Buy and Sell Stock with Cooldown (LeetCode 309)”

Unlimited trades, but after selling you must skip a day before buying. The trick: a small state machine DP with three states per day (holding, just sold, resting), each depending on the previous day’s states. O(n) time, O(1) space.

Best Time to Buy and Sell Stock with Transaction Fee (LeetCode 714)

Section titled “Best Time to Buy and Sell Stock with Transaction Fee (LeetCode 714)”

Unlimited trades, but each sale costs a fee. The trick: a two-state hold/cash DP, like the 309 one, with the fee subtracted when you sell. No cooldown state needed.