Optimal Single Buy-and-Sell Gain

Easy · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given an integer list prices where prices[i] records an asset's price on day i, implement max_profit(prices) to return the largest net gain obtainable from at most one round-trip trade: purchasing a single unit on day b and selling it on a strictly later day s (0 <= b < s < len(prices)), earning prices[s] - prices[b].

Making zero trades is allowed and earns 0. Whenever no later day beats an earlier buy price (such as a single-day schedule or a non-increasing sequence), return 0.

Examples

Example 1

Input:  prices = [9, 3, 7, 4, 10, 6]
Output: 7

Walk-through: Purchasing on day 1 at 3 and selling on day 4 at 10 yields 10 - 3 = 7, the highest single-trade gain available.

Example 2

Input:  prices = [12, 9, 8, 5, 2]
Output: 0

Walk-through: Every subsequent day is cheaper than every prior day, so any trade loses money; doing zero trades returns 0.

Example 3

Input:  prices = [6, 9]
Output: 3

Walk-through: Purchasing on day 0 at 6 and selling on day 1 at 9 earns 9 - 6 = 3.

Example 4

Input:  prices = [5, 11, 2, 8, 1, 9]
Output: 8

Walk-through: Early rebound 5 -> 11 earns 6 and mid-schedule rebound 2 -> 8 also earns 6, whereas waiting for day 4's low of 1 and selling on day 5 at 9 earns 9 - 1 = 8.

Constraints

  • 1 <= len(prices) <= 2 * 10^5
  • -10^9 <= prices[i] <= 10^9

Step-by-step walkthrough

  1. Understand the goal and rules

    We are given a list prices where prices[i] is the daily price on day i. We want the largest gain obtainable from at most one trade: buying on some day buy and selling on a strictly later day sell > buy, earning prices[sell] - prices[buy].

    Two rules shape the entire algorithm:

    • Time moves one way (buy < sell). We cannot simply compute max(prices) - min(prices), because the lowest price might appear after the highest price. On [3, 8, 1, 2], 8 - 1 = 7 is invalid because 8 occurred before 1; the best valid trade buys at 3 and sells at 8 for 5.
    • Zero trades is allowed. On a single-day schedule or a sequence that never rises (such as [12, 9, 8, 5, 2]), every trade loses or makes 0, so we skip trading and return 0. The result is never negative.
  2. Start with brute force and see why it is slow

    The most direct check tries every valid (buy, sell) pair with buy < sell and tracks the largest gain above 0:

    def brute_max_profit(prices):
        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
    

    Across n days, there are n * (n - 1) / 2 pairs. At n = 200,000, that is roughly 20 billion subtractions — far too slow. Notice why it repeats work: for each sell day, the inner loop re-scans the past from scratch to find the cheapest earlier buy day.

  3. Key insight: track the cheapest earlier buy day

    Flip your viewpoint and ask: Suppose I sell on day day. Which earlier day should I have bought on?

    To maximize prices[day] - prices[buy] across all buy < day, prices[buy] should be as small as possible. No other past price matters — only the minimum price seen across days 0 through day - 1.

    Day index:    0    1    2    3    4    5
    Price:        9    3    7    4   10    6
                       ^              ^
                cheapest past     sell here:
                 buy = 3       10 - 3 = 7 (best!)
    

    Advancing from day to day + 1 updates that running minimum with a single comparison: min(old_min, prices[day]). That turns an O(n) lookback per day into O(1) work!

  4. Write the single-pass loop

    Maintain two integers while scanning day = 1 through len(prices) - 1:

    • min_buy_price: lowest price seen on strictly earlier days (0 .. day - 1), initialized to prices[0].
    • best_profit: highest gain found so far, initialized to 0 (representing zero trades).

    Two implementation details keep the code clean and O(1)-space:

    1. Loop with for day in range(1, len(prices)): instead of for price in prices[1:]:, because slicing prices[1:] in Python copies n - 1 elements and uses O(n) extra memory rather than O(1).
    2. Compute profit_today = sell_price - min_buy_price before updating min_buy_price, guaranteeing min_buy_price always comes from a strictly earlier day.
    def max_profit(prices: List[int]) -> int:
        if not prices:
            return 0
    
        # min_buy_price: int — lowest stock price seen on any strictly earlier day (days 0 .. day - 1)
        min_buy_price = prices[0]
        # best_profit: int — highest profit achievable so far; starts at 0 because doing 0 trades is allowed
        best_profit = 0
    
        # Phase 1: scan each potential sell day from day 1 onward (avoid slicing prices[1:] to keep O(1) space)
        for day in range(1, len(prices)):
            sell_price = prices[day]
    
            # Phase 2: check the profit if we bought at the cheapest earlier day and sold today
            profit_today = sell_price - min_buy_price
            if profit_today > best_profit:
                best_profit = profit_today
    
            # Phase 3: update min_buy_price AFTER checking today's sale so we never buy and sell on the same day
            if sell_price < min_buy_price:
                min_buy_price = sell_price
    
        return best_profit
    
  5. Trace through concrete examples

    Let's trace Example 1, prices = [9, 3, 7, 4, 10, 6]. Before the loop starts, min_buy_price = 9 (day 0) and best_profit = 0:

    day | sell_price | min_buy_price (before) | profit_today | best_profit | min_buy_price (after)
    ----+------------+------------------------+--------------+-------------+----------------------
      1 |          3 |                      9 |   3 - 9 = -6 |           0 |                     3
      2 |          7 |                      3 |   7 - 3 =  4 |           4 |                     3
      3 |          4 |                      3 |   4 - 3 =  1 |           4 |                     3
      4 |         10 |                      3 |  10 - 3 =  7 |           7 |                     3
      5 |          6 |                      3 |   6 - 3 =  3 |           7 |                     3
    

    The loop finishes and returns 7 (buy on day 1 at 3, sell on day 4 at 10).

    On Example 2, prices = [12, 9, 8, 5, 2], every day is below min_buy_price, so profit_today is negative on every iteration, best_profit stays 0, and we return 0.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def max_profit(prices: List[int]) -> int:
        if not prices:
            return 0
    
        # min_buy_price: int — lowest stock price seen on any strictly earlier day (days 0 .. day - 1)
        min_buy_price = prices[0]
        # best_profit: int — highest profit achievable so far; starts at 0 because doing 0 trades is allowed
        best_profit = 0
    
        # Phase 1: scan each potential sell day from day 1 onward (avoid slicing prices[1:] to keep O(1) space)
        for day in range(1, len(prices)):
            sell_price = prices[day]
    
            # Phase 2: check the profit if we bought at the cheapest earlier day and sold today
            profit_today = sell_price - min_buy_price
            if profit_today > best_profit:
                best_profit = profit_today
    
            # Phase 3: update min_buy_price AFTER checking today's sale so we never buy and sell on the same day
            if sell_price < min_buy_price:
                min_buy_price = sell_price
    
        return best_profit
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine stepping forward through a calendar of daily prices while carrying a single sticky note. On that sticky note, you keep the cheapest price seen on any earlier day. Each time you step onto a new day, you ask one question: "If I had bought at the price on my sticky note and sold today, would that beat my best gain so far?" After checking, if today's price is even cheaper than what is written on the note, you update the note with today's price for future days to use.

The brute-force approach checks every (buy, sell) pair of days with nested loops, repeating the search for the cheapest past day over and over in O(n^2) time. Another tempting shortcut — returning max(prices) - min(prices) — fails whenever the global minimum occurs after the global maximum, which would sell before buying. Maintaining a prefix minimum (a running minimum of all elements from index 0 up to the previous index) supplies the exact optimal buy price for every candidate sell day in constant time.

Let's walk through a 4-day trace, prices = [8, 2, 7, 4]:

  • Start after day 0: min_buy_price = 8, best_profit = 0.
  • Day 1 (price = 2): selling today gives 2 - 8 = -6 (below 0), then 2 < 8 updates min_buy_price to 2.
  • Day 2 (price = 7): selling today gives 7 - 2 = 5, updating best_profit to 5; min_buy_price stays 2.
  • Day 3 (price = 4): selling today gives 4 - 2 = 2 (below 5), and 4 is not below 2. Return best_profit = 5.

Complexity

  • Time: O(n), where n is len(prices). We visit each day from index 1 to n - 1 once and perform a single subtraction and two comparisons per day.
  • Space: O(1) auxiliary space. Regardless of how long prices is, we store only a fixed set of integer variables (min_buy_price, best_profit, day, sell_price, profit_today) and iterate by index rather than slicing the list.

Edge cases

  • Single day ([5]): range(1, 1) is empty, so no sell day exists and the function immediately returns 0.
  • Strictly decreasing or flat prices ([12, 9, 8, 5, 2], [3, 3, 3]): every candidate trade yields a negative or zero difference, so best_profit remains 0.
  • Global minimum after global maximum ([3, 8, 1, 2]): 8 sees min_buy_price = 3 (gain 5), and only later does min_buy_price drop to 1 (giving 2 - 1 = 1 on the final day), so 5 wins instead of 8 - 1 = 7.
  • Late dip with an even larger rebound ([5, 11, 2, 8, 1, 9]): best_profit first reaches 11 - 5 = 6, then min_buy_price drops to 2 and later 1, allowing day 5 to reach 9 - 1 = 8.
  • Negative values ([-5, -2, -10, -1]): subtraction measures exact gain (-1 - (-10) = 9), and all-decreasing negatives like [-2, -5, -9] still return 0.

Common mistakes

  • Returning max(prices) - min(prices): ignores chronological order and pairs an early peak with a later trough.
  • Initializing best_profit to -inf or prices[1] - prices[0]: returns a negative number on falling schedules when zero trades (0 gain) is allowed, and indexing prices[1] crashes on a 1-element list.
  • Writing for price in prices[1:]: while claiming O(1) space: list slicing in Python copies n - 1 elements into a new list, quietly using O(n) extra memory.
  • Resetting best_profit when min_buy_price updates: a lower buy price found late in the array might never be followed by a high sell price (as in [3, 8, 1, 2]), so earlier gains must stay recorded.

Alternative approaches

  • Kadane's algorithm on daily price changes: Kadane's algorithm is a single-pass method that finds the contiguous subarray with the largest sum by resetting a running total to 0 whenever it dips below 0. Since prices[sell] - prices[buy] equals the telescoping sum of daily changes (prices[buy + 1] - prices[buy]) + ... + (prices[sell] - prices[sell - 1]), running Kadane's algorithm on adjacent differences produces the exact same O(n) time and O(1) space result.
  • Right-to-left suffix maximum scan: A suffix maximum is the largest value from a given index through the end of the array. Scanning backward while tracking the highest future sell price seen so far and testing each day as a buy day is symmetric and also runs in O(n) time and O(1) space.

Follow-up questions

  • How would you return the buy and sell day indices that achieve the maximum gain instead of only the gain value? Track min_buy_day = 0 alongside min_buy_price, updating min_buy_day = day whenever sell_price < min_buy_price. Whenever profit_today > best_profit, save best_pair = (min_buy_day, day). If best_profit remains 0, return None (or (-1, -1) per the caller's convention), all in O(n) time and O(1) space.
  • How does the algorithm change if you may execute unlimited non-overlapping trades while holding at most one share at any time? Every multi-day rise from day i to day j equals the sum of the single-day changes in between, so collecting every positive adjacent difference max(0, prices[day] - prices[day - 1]) earns at least as much as any set of non-overlapping trades. Summing all positive daily steps solves it in O(n) time and O(1) space.
  • What if you are capped at most k buy-sell transactions across the entire schedule? Use dynamic programming — breaking the problem into overlapping subproblems and updating best-so-far balances day by day — keeping two arrays of length k + 1: best_hold[t] (highest cash balance while holding a unit during trade t) and best_sold[t] (highest cash balance after completing t trades). Each day updates all k states in O(k) work, running in O(n * k) time and O(k) space (or reducing immediately to the O(n) unlimited-trades pass whenever k >= n // 2).

Follow-up questions

Similar questions

More Flipster interview questions

All 2 Flipster questions →