Optimal Gain from a Single Share Transaction

Medium · Coding & Algorithms · Backend Engineer · Onsite

Problem Statement

Given an integer list prices where prices[i] records the price of one share on day i (0-indexed), compute the largest net gain obtainable from at most one trade.

A valid trade buys a single share on some day b and sells that share on a strictly later day s (0 <= b < s < len(prices)), earning prices[s] - prices[b]. Buying and selling on the same day is not allowed, and selling cannot happen before buying. If every valid pair of days breaks even or loses money—or if fewer than two days exist—do not trade and return 0.

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

Examples

Example 1

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

Purchasing on day 1 at 3 and selling on day 4 at 10 earns 10 - 3 = 7. Although 9 appears on day 0, you cannot sell at 9 and buy later at 3 because the purchase day must precede the sale day.

Example 2

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

Quotes drop every day, so every legal (buy, sell) pair has prices[sell] < prices[buy]. Skipping the trade yields 0.

Constraints

  • 1 <= len(prices) <= 10^5
  • 0 <= prices[i] <= 10^9

Step-by-step walkthrough

  1. Understand the time-order rule

    We are given daily share quotes prices[0 .. n - 1]. We may choose at most one index buy to purchase a share and a strictly later index sell > buy to sell it, earning prices[sell] - prices[buy]. Whenever every legal pair loses money (or prices has length 1), we skip trading and return 0.

    Why can't we just return max(prices) - min(prices)? Because time only moves forward — you cannot sell on day 0 and buy on day 1:

    prices = [9, 3, 7, 4, 10, 6]
    
    Price
     10 |                 *  <-- Sell on Day 4 at 10 (gain = 10 - 3 = 7)
      9 | *                      (Day 0 quote comes BEFORE Day 1's dip)
      7 |         *
      6 |                     *
      4 |             *
      3 |     *  <-------------- Buy on Day 1 at 3
        +------------------------
          0   1   2   3   4   5   Day
    

    With up to 100,000 days and quotes up to 10^9, we want a single O(n) pass that enforces buy < sell.

  2. Brute force: check every `(buy, sell)` pair

    The most direct way to obey buy < sell is to test every possible buy day against every later sell day:

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

    This checks n * (n - 1) / 2 pairs. At n = 100,000, that is roughly 5 * 10^9 subtractions — accurate for short lists, but far too slow for the full constraint. Notice why it repeats work: for each sell day, it rescans all earlier days from scratch just to rediscover which earlier day was cheapest.

  3. Key idea: fix the sell day and track the cheapest past buy day

    Flip the perspective from choosing the buy day first to evaluating each sell day as we walk forward:

    If we sell on day (for day >= 1), which earlier index 0 .. day - 1 gives the best purchase price?

    Since prices[day] is fixed, prices[day] - prices[buy] is largest when prices[buy] is as small as possible:

    Best gain when selling on `day`  =  prices[day] - min(prices[0 .. day - 1])
    

    That prefix minimum does not need to be recomputed from scratch. As we advance one day at a time, we carry a single running variable lowest_buy_price:

    • Before inspecting day, lowest_buy_price already equals min(prices[0 .. day - 1]).
    • After checking the gain of selling on day, we update lowest_buy_price = min(lowest_buy_price, prices[day]) so it is ready for day + 1.
  4. Code the single left-to-right pass

    We initialize: - lowest_buy_price = prices[0] (day 0 is the only candidate buy day before day 1), - best_profit = 0 (making zero trades is always allowed).

    Then we loop day from 1 to len(prices) - 1. Notice two clean properties of this loop: 1. Single-day lists (len(prices) == 1): range(1, 1) executes zero iterations and returns 0, matching the rule that buying and selling require two distinct days. 2. Update order inside the loop: We compute profit_if_sold_today before folding today_price into lowest_buy_price. That guarantees a share is never bought and sold on the exact same day (which also keeps the logic bug-free if a variant ever requires making a trade even at a loss).

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def max_profit(prices: List[int]) -> int:
        # lowest_buy_price: minimum stock price seen across all earlier days 0 .. day - 1
        lowest_buy_price = prices[0]
        # best_profit: highest profit from one valid buy-then-sell trade (0 = skip trading)
        best_profit = 0
    
        # Start on day 1 because selling requires a strictly earlier buy day.
        for day in range(1, len(prices)):
            today_price = prices[day]
    
            # Phase 1: Best profit if we sell today is today's price minus the cheapest past day.
            profit_if_sold_today = today_price - lowest_buy_price
            if profit_if_sold_today > best_profit:
                best_profit = profit_if_sold_today
    
            # Phase 2: Only after checking today's sale can today become a buy option for future days.
            if today_price < lowest_buy_price:
                lowest_buy_price = today_price
    
        return best_profit
    
  5. Trace Examples 1 and 2 day by day

    Example 1: prices = [9, 3, 7, 4, 10, 6] (starts with lowest_buy_price = 9, best_profit = 0)

    day  today_price  lowest_buy_price (before)  profit_if_sold_today  best_profit  lowest_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
    

    Returned answer: 7 (buy at 3 on day 1, sell at 10 on day 4).

    Example 2: prices = [12, 9, 8, 5, 2] (starts with lowest_buy_price = 12, best_profit = 0)

    day  today_price  lowest_buy_price (before)  profit_if_sold_today  best_profit  lowest_buy_price (after)
    --------------------------------------------------------------------------------------------------------
     1        9                 12                   9 - 12 = -3            0                  9
     2        8                  9                   8 -  9 = -1            0                  8
     3        5                  8                   5 -  8 = -3            0                  5
     4        2                  5                   2 -  5 = -3            0                  2
    

    Every profit_if_sold_today is negative, so best_profit stays 0.

  6. Full solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def max_profit(prices: List[int]) -> int:
        # lowest_buy_price: minimum stock price seen across all earlier days 0 .. day - 1
        lowest_buy_price = prices[0]
        # best_profit: highest profit from one valid buy-then-sell trade (0 = skip trading)
        best_profit = 0
    
        # Start on day 1 because selling requires a strictly earlier buy day.
        for day in range(1, len(prices)):
            today_price = prices[day]
    
            # Phase 1: Best profit if we sell today is today's price minus the cheapest past day.
            profit_if_sold_today = today_price - lowest_buy_price
            if profit_if_sold_today > best_profit:
                best_profit = profit_if_sold_today
    
            # Phase 2: Only after checking today's sale can today become a buy option for future days.
            if today_price < lowest_buy_price:
                lowest_buy_price = today_price
    
        return best_profit
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine flipping through a ledger of daily share quotes one page at a time while keeping a single sticky note with the cheapest quote seen on any earlier page. Each time you turn to a new day, you ask one simple question: "If I had bought on that cheapest earlier day and sold today, how much would I clear?" By tracking both that cheapest earlier quote (lowest_buy_price) and the best gain seen so far (best_profit, initialized to 0 since sitting out costs nothing), a single left-to-right pass evaluates the optimal buy day for every candidate sell day.

Simply computing max(prices) - min(prices) fails whenever the peak appears before the trough, because you cannot sell a share before buying it. Locking onto the overall minimum quote and only checking days after it also fails (for example, in [2, 9, 1, 4], buying at 2 and selling at 9 earns 7, whereas waiting for the global low 1 only earns 3). Testing every (buy, sell) pair with two nested loops is exact, but across 100,000 days it performs roughly 5 billion subtractions and times out.

Trace prices = [8, 3, 7, 2]. Before the loop, Day 0 sets lowest_buy_price = 8 and best_profit = 0. On Day 1 (price = 3), selling today yields 3 - 8 = -5 (best_profit stays 0), and lowest_buy_price drops to 3. On Day 2 (price = 7), selling today yields 7 - 3 = 4, raising best_profit to 4 while lowest_buy_price stays 3. On Day 3 (price = 2), selling today yields 2 - 3 = -1 (best_profit stays 4) and lowest_buy_price drops to 2 — then the loop ends and returns 4.

Complexity

Let n = len(prices) be the number of days.

  • Time: O(n). Starting at index 1, we inspect each of the n - 1 remaining quotes once and perform one subtraction plus two comparisons (O(1) work) per day.
  • Space: O(1). Whether prices holds 1 quote or 100,000 quotes, we store only four scalar integer variables (lowest_buy_price, best_profit, today_price, and profit_if_sold_today).

Edge cases

  • Single day (len(prices) == 1): range(1, 1) runs zero iterations and immediately returns 0, since no later sell day exists.
  • Strictly decreasing quotes ([12, 9, 8, 5, 2]): Every profit_if_sold_today is negative, so best_profit stays 0.
  • Flat quotes ([4, 4, 4, 4]): Every trade earns 0, returning 0.
  • Peak before trough ([3, 8, 1, 2]): Returns 8 - 3 = 5 rather than 8 - 1 = 7, because lowest_buy_price only summarizes earlier days.
  • Best trade ignores the global minimum ([2, 9, 1, 4]): best_profit records 9 - 2 = 7 on Day 1 and preserves it even after lowest_buy_price drops to 1 on Day 2.
  • Extreme quote bounds (0 and 10^9): [0, 10**9] yields 10^9, fitting comfortably in standard signed 32-bit and Python integers.

Common mistakes

  • Computing max(prices) - min(prices): Violates buy < sell whenever a high quote precedes the cheapest dip, such as [12, 9, 8, 5, 2] or [3, 8, 1, 2].
  • Finding argmin(prices) first and scanning only to its right: Misses larger gains that finish before the global minimum arrives, such as [2, 9, 1, 4].
  • Initializing best_profit to float('-inf') or prices[1] - prices[0]: Returns a negative value on falling quotes instead of 0 (and prices[1] raises IndexError when len(prices) == 1).
  • Updating lowest_buy_price before computing profit_if_sold_today: Permits a phantom same-day buy-and-sell of 0 — harmless when best_profit starts at 0, but buggy if a variant forces a trade on falling markets.

Alternative approaches

  • Kadane's algorithm on day-to-day changes: Because prices[sell] - prices[buy] equals the telescoping sum (prices[buy + 1] - prices[buy]) + ... + (prices[sell] - prices[sell - 1]), the problem is equivalent to finding the maximum subarray sum (the contiguous slice of numbers with the largest total) of daily differences via Kadane's algorithm — scanning left to right while clamping any negative running sum back to 0 — in the same O(n) time and O(1) space.

Follow-up questions

  • How would you extend the algorithm when up to two non-overlapping buy-sell trades are permitted? Maintain four best-so-far cash balances as each quote p arrives: after_buy1 (highest balance after buying the first share, starting at -prices[0]), after_sell1 (after selling the first share, 0), after_buy2 (after reinvesting after_sell1 into a second share, -prices[0]), and after_sell2 (after selling the second share, 0). Updating after_buy1 = max(after_buy1, -p), after_sell1 = max(after_sell1, after_buy1 + p), after_buy2 = max(after_buy2, after_sell1 - p), and after_sell2 = max(after_sell2, after_buy2 + p) solves the two-trade problem in O(n) time and O(1) space.
  • What changes if selling a share always deducts a constant brokerage fee? When you are still capped at one trade, every trade pays the same fee, so the optimal pair of days never changes and the answer is max(0, max_profit(prices) - fee). When unlimited sequential trades are allowed with fee per sale, track two running states — cash (best balance holding zero shares, initialized to 0) and hold (best balance holding one share, initialized to -prices[0]) — and update cash, hold = max(cash, hold + p - fee), max(hold, cash - p) in O(n) time and O(1) space.
  • How would you maintain the best achievable gain in real time over an unbounded live tick feed? An online algorithm processes each arriving item immediately without knowing future inputs or keeping the entire history in memory. Our one-pass loop is already online: store only lowest_buy_price and best_profit, update both in O(1) time per incoming quote, and answer queries in O(1) time using O(1) space forever. (If trades must instead fall inside a sliding window of the latest W ticks, old minimums expire, so you can maintain a fixed-capacity segment tree over the last W ticks storing (min_price, max_price, best_gain) per node for O(log W) updates.)

Follow-up questions

Similar questions

More Oracle interview questions

All 104 Oracle questions →