Best Time to Buy and Sell Stock

Free with account Updated Nov 19, 2026 · 4 min read
On this page

    Problem statement

    You are given a list of daily prices for one stock. Choose one day to buy and a later day to sell to make the largest profit, and return that profit. If no profit is possible, return 0. You must buy before you sell, and you make exactly one transaction at most.

    It's an easy problem with a pattern you'll reuse constantly: walk once and keep the best thing seen so far (here, the cheapest price) to compare against the current element. Original problem: LeetCode 121.

    Example

    Buying on day 1 at price 1 and selling on day 4 at price 6 gives the largest profit, 5.
    Buying on day 1 at price 1 and selling on day 4 at price 6 gives the largest profit, 5.
    Input:  [7, 1, 5, 3, 6, 4]
    Output: 5        # buy at 1 (day 1), sell at 6 (day 4)
    Input:  [7, 6, 4, 3, 1]
    Output: 0        # prices only fall; don't trade

    Constraints (assumed)

    • 1 ≤ n ≤ 100,000.
    • 0 ≤ price ≤ 10,000.

    What this question tests

    • Replacing an all-pairs search with a running minimum.
    • Respecting order: the buy must come before the sell.
    • A clean O(n), O(1) solution and a clear explanation of why it's correct.

    Questions to ask first

    1. One transaction, or as many as I like? (Here: one. Unlimited trades is a different, greedy problem.)
    2. Can I buy and sell on the same day? It gives profit 0, so it doesn't change the answer.
    3. Return the profit or the days? (Here: the profit; returning days needs two extra variables.)
    4. What if no profit is possible? (Here: 0.)