Best Single-Trade Stock Gain

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given a list of non-negative integers prices, where prices[d] denotes the market quote of a single share on day d (0-indexed), determine the largest net gain obtainable from at most one trade.

A valid trade consists of purchasing one share on some day buy and selling that share on a strictly later day sell (0 <= buy < sell < len(prices)), earning prices[sell] - prices[buy]. If every valid pair of days yields zero or negative gain—or if fewer than two days exist—skip trading altogether and return 0.

def max_profit(prices: List[int]) -> int:

Examples

Example 1

Input:  prices = [9, 3, 7, 2, 10, 5]
Output: 8

Buying on day 3 at 2 and selling on day 4 at 10 earns 10 - 2 = 8. An earlier trade from day 1 (3) to day 2 (7) only earns 4, and the opening quote of 9 on day 0 cannot be used as a sale price for any later purchase.

Example 2

Input:  prices = [12, 10, 8, 8, 3]
Output: 0

Quotes never rise above an earlier day's level, so any purchase followed by a later sale either breaks even (8 - 8 = 0) or loses money. Making no trade yields 0.

Constraints

  • 1 <= len(prices) <= 10^5
  • 0 <= prices[d] <= 10^4

Step-by-step walkthrough

  1. Restate the problem

    We receive a list prices where prices[day] gives the share quote on day. We may purchase one share on some index buy and sell it on a strictly later index sell (buy < sell). We want to return the largest possible gain prices[sell] - prices[buy], or 0 when every legal trade breaks even or loses money.

    Because time moves forward, max(prices) - min(prices) does not work whenever the peak comes before the trough (for instance, [9, 2, 6, 1] has 9 - 1 = 8, yet the best chronological trade buys at 2 and sells at 6 for 4).

  2. Brute force first and why it is too slow

    A direct nested scan pairs every buy index with every subsequent sell index:

    def max_profit_brute(prices: list[int]) -> int:
        best_profit = 0
        for buy in range(len(prices)):
            for sell in range(buy + 1, len(prices)):
                profit = prices[sell] - prices[buy]
                if profit > best_profit:
                    best_profit = profit
        return best_profit
    

    Checking n * (n - 1) / 2 day pairs requires around 5 * 10^9 iterations at n = 10^5, which is far too slow. Notice the repeated effort: for every candidate sell day, the inner loop re-scans the entire prefix just to rediscover the cheapest historical quote.

  3. Key idea: fix the sell day and remember the lowest quote so far

    Turn the question around: if we sell on day, which earlier day 0 .. day - 1 would have been the best day to buy? Always the cheapest earlier day, since subtracting the smallest prior quote maximizes prices[day] - min_price_so_far.

    Rather than re-scanning earlier days from scratch, we carry min_price_so_far forward in a single left-to-right pass:

    prices:            [ 9,   3,   7,   2,  10,   5 ]
    day index:           0    1    2    3    4    5
    min_price_so_far:    9 -> 3 -> 3 -> 2 -> 2 -> 2
    sell today profit:   -   -6   +4   -1   +8   +3
    best_profit:         0    0    4    4    8    8
    

    For each day from 1 through len(prices) - 1: 1. Evaluate profit_if_sold_today = prices[day] - min_price_so_far and raise best_profit if we beat our best gain. 2. Lower min_price_so_far when prices[day] sets a new historical low for future selling days.

  4. Trace Example 1 and Example 2

    Let's walk through Example 1, prices = [9, 3, 7, 2, 10, 5]:

    Start (day 0): min_price_so_far = 9, best_profit = 0
    
    day 1 (price = 3):  profit_if_sold_today = 3 - 9 = -6  -> best_profit stays 0
                        3 < 9 -> min_price_so_far becomes 3
    day 2 (price = 7):  profit_if_sold_today = 7 - 3 = 4   -> best_profit becomes 4
                        7 < 3 is False -> min_price_so_far stays 3
    day 3 (price = 2):  profit_if_sold_today = 2 - 3 = -1  -> best_profit stays 4
                        2 < 3 -> min_price_so_far becomes 2
    day 4 (price = 10): profit_if_sold_today = 10 - 2 = 8  -> best_profit becomes 8
                        10 < 2 is False -> min_price_so_far stays 2
    day 5 (price = 5):  profit_if_sold_today = 5 - 2 = 3   -> best_profit stays 8
                        5 < 2 is False -> min_price_so_far stays 2
    
    Return best_profit = 8 (bought at 2 on index 3, sold at 10 on index 4).
    

    On Example 2, prices = [12, 10, 8, 8, 3], profit_if_sold_today takes values -2, -2, 0, -5 across days 1..4, so best_profit stays at its initial 0 (representing no trade).

  5. Complete solution

    Day 0 has no prior day to buy from, so we seed min_price_so_far = prices[0] and sweep from day = 1 onward:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def max_profit(prices: List[int]) -> int:
        # min_price_so_far: lowest stock price seen on any earlier day in prices[0..day - 1]
        min_price_so_far = prices[0]
        # best_profit: highest profit found so far; starts at 0 because skipping all trades gives 0
        best_profit = 0
    
        # Sweep from day 1 onward, treating each day as a candidate selling day
        for day in range(1, len(prices)):
            today_price = prices[day]
            profit_if_sold_today = today_price - min_price_so_far
    
            # Check profit before updating min_price_so_far so the buy day is strictly before today
            if profit_if_sold_today > best_profit:
                best_profit = profit_if_sold_today
    
            # Record a new historical low if today is cheaper for future selling days
            if today_price < min_price_so_far:
                min_price_so_far = today_price
    
        return best_profit
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine walking forward through a historical quote chart while holding a sticky note with the lowest quote seen on any earlier day. Each morning, before updating the sticky note, you ask one question: "If I had bought on that cheapest past day and sold right now, how much would I earn?" Afterward, if today's quote beats the low on your note, you write today's number down for tomorrow and beyond. Tracking that running low in one left-to-right pass is a prefix-minimum sweep (maintaining the smallest element of prices[0..day - 1] incrementally as day advances).

Why do obvious shortcuts fail? Checking every (buy, sell) pair with nested loops inspects roughly n^2 / 2 pairs — around 5 billion steps at n = 100,000 — because it searches the past from scratch on every sell day. Meanwhile, taking max(prices) - min(prices) ignores time order and gives wrong answers whenever the peak precedes the valley or the overall minimum lands near the end after a larger earlier rally.

Here is a 4-day walkthrough where the global low arrives too late, prices = [2, 9, 1, 3]:

day 0 (price 2): seed min_price_so_far = 2, best_profit = 0
day 1 (price 9): sell today -> 9 - 2 = 7 -> best_profit = 7; min stays 2
day 2 (price 1): sell today -> 1 - 2 = -1; new low! min_price_so_far = 1
day 3 (price 3): sell today -> 3 - 1 = 2 (less than 7); min stays 1

Result: 7 (bought at 2, sold at 9 — even though 1 was the overall minimum!).

Complexity

  • Time: O(n), where n is len(prices). We visit each index from 1 to n - 1 once and do a constant number of comparisons and subtractions (O(1) work) per element.
  • Space: O(1) auxiliary space. Only four scalar variables (min_price_so_far, best_profit, today_price, and profit_if_sold_today) are kept in memory, with no extra lists or slices allocated.

Edge cases

  • Single-day input ([5] or [0]): Buying and selling require two distinct days; range(1, 1) is empty, so the loop does not run and 0 is returned.
  • Non-increasing or constant quotes ([12, 10, 8, 8, 3], [4, 4, 4]): Every profit_if_sold_today is <= 0, leaving best_profit at 0.
  • Optimal buy is not the global low ([2, 9, 1, 3]): Buying at 2 and selling at 9 yields 7, whereas buying at the later global low 1 only yields 3 - 1 = 2. Testing every day against the running prefix low captures both early and late rallies.
  • Zero-priced shares ([0, 10000]): Quotes down to 0 are permitted by the constraints; buying at 0 and selling at 10000 cleanly returns 10000.

Common mistakes

  • Computing max(prices) - min(prices): That sells before buying whenever the highest quote appears before the lowest quote (returning 8 instead of 4 on [9, 2, 6, 1]).
  • Only scanning to the right of min(prices): Locating the global minimum first and taking the highest value after it misses bigger gains that happened before the global low (returning 2 instead of 7 on [2, 9, 1, 3]).
  • Seeding best_profit with float("-inf") or prices[1] - prices[0]: On falling inputs such as [12, 10, 8, 8, 3], that returns a negative number instead of 0.
  • Looping over a slice prices[1:]: In Python, prices[1:] copies n - 1 elements into a new list, silently turning O(1) auxiliary space into O(n). Indexing via range(1, len(prices)) keeps extra memory constant.

Alternative approaches

  • Kadane's algorithm on day-to-day differences: Any trade gain prices[sell] - prices[buy] equals the telescoping sum of daily steps (prices[buy + 1] - prices[buy]) + ... + (prices[sell] - prices[sell - 1]). Computing the maximum subarray sum (the contiguous slice of daily changes with the largest total, clamped at 0, known as Kadane's algorithm) achieves the same O(n) time and O(1) space.
  • Right-to-left suffix-maximum pass: Sweep backward from the final day while tracking max_future_price to the right, testing each day as a candidate purchase day (max_future_price - prices[day]).

Follow-up questions

  • Suppose you may execute unlimited buy-sell cycles while holding at most one share at any time—how does the algorithm change? Add every positive day-over-day increase max(0, prices[d] - prices[d - 1]) across d = 1 .. n - 1 in O(n) time and O(1) space. Because any multi-day rally such as 2 -> 5 -> 9 (9 - 2 = 7) equals the sum of its upward daily steps (5 - 2) + (9 - 5) = 3 + 4 = 7, summing every upward step captures all profitable swings without holding through dips.
  • How would you adapt a multi-trade strategy if selling a share enforces a one-day rest period before your next purchase? Use dynamic programming (maintaining optimal values across a small set of states step by step) with three scalar balances per day: holding (best cash balance while owning a share), just_sold (best cash balance after selling today), and ready (best cash balance while flat and eligible to buy). Updating holding, just_sold, ready = max(holding, ready - price), holding + price, max(ready, just_sold) for each quote solves the problem in O(n) time and O(1) space.
  • What additional state is needed to output the (buy_day, sell_day) index pair rather than just the profit? Store min_day = 0 (the index where min_price_so_far occurred) alongside best_profit = 0 and best_days = None. Whenever prices[day] - prices[min_day] > best_profit, update both best_profit and best_days = (min_day, day), and whenever prices[day] < prices[min_day], set min_day = day; if best_days remains None at the end, no profitable trade exists.

Follow-up questions

Similar questions

More Xiaohongshu interview questions

All 2 Xiaohongshu questions →