Tensorum
LeetCode 121 · State Machine / Stocks

Best Time to Buy and Sell Stock

LeetCode 121 · Easy · solution, intuition & step-by-step walkthrough

profit(i) = price[i] − min(prices[0..i]).

EasyArrayDynamic Programming
48 msruntime · beats 62%
28.5 MBmemory · beats 68%
1approach
17accepted runs · last 26 May 2026

This is how I solved Best Time to Buy and Sell Stock (LeetCode 121), an easy problem from the State Machine / Stocks pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

If you sell on day i, the best buy day is simply the cheapest price before it. So walk forward remembering the minimum price so far and ask, every day, how much you'd make selling today.

Approach

  1. 1

    min_buy tracks the lowest price seen so far.

  2. 2

    For each price, update min_buy first, then compare price − min_buy against the best profit.

  3. 3

    If prices only fall, the best profit stays 0 (don't trade).

How I solved it

One pass, running minimumPythonO(n) time · O(1) space
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_buy = prices[0]
        max_profit= 0
        for price in prices:
            min_buy = min(price,min_buy)
            max_profit = max(max_profit,price-min_buy)
        return max_profit
Loading the step-through…

Best Time to Buy and Sell Stock — FAQ

What is the intuition behind Best Time to Buy and Sell Stock?

If you sell on day i, the best buy day is simply the cheapest price before it. So walk forward remembering the minimum price so far and ask, every day, how much you'd make selling today.

How do you solve Best Time to Buy and Sell Stock (LeetCode 121)?

1. min_buy tracks the lowest price seen so far. 2. For each price, update min_buy first, then compare price − min_buy against the best profit. 3. If prices only fall, the best profit stays 0 (don't trade).

What is the time and space complexity of Best Time to Buy and Sell Stock?

Time: O(n). Space: O(1). (Accepted approach: One pass, running minimum.)

What are common mistakes in Best Time to Buy and Sell Stock?

You must buy before you sell — max(prices) − min(prices) ignores order.