Maximum Stock Profit Under Mandatory Trades

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given a 0-indexed list prices where prices[d] represents the price of one share on day d, compute the highest achievable net profit under a mandatory-trade rule:

def profit_exactly_one(prices: List[int]) -> Optional[int]: ...
def profit_exactly_two(prices: List[int]) -> Optional[int]: ...

Rules & Modeling Assumptions

  • Trading mechanics: Each transaction buys 1 share on one day and sells that share on a strictly later day (buy < sell), with zero transaction fees and no short selling (you may hold at most 1 share at any time).
  • profit_exactly_one(prices): Select indices 0 <= buy < sell < len(prices) maximizing prices[sell] - prices[buy]. Even if share prices fall every single day, the trade is still required—return the smallest possible loss (a negative integer). Return None when len(prices) < 2.
  • profit_exactly_two(prices): Select four strictly increasing indices 0 <= buy1 < sell1 < buy2 < sell2 < len(prices) (the first share must be sold strictly before the day the second share is purchased) maximizing (prices[sell1] - prices[buy1]) + (prices[sell2] - prices[buy2]). Unavoidable losses must still be taken to complete both trades. Return None when len(prices) < 4.

Examples

Example 1

Input:  prices = [2, 9, 4, 11, 3, 6]
Output:
  profit_exactly_one(prices) -> 9
  profit_exactly_two(prices) -> 14

Explanation: - For a single trade, buying on day 0 (2) and selling on day 3 (11) earns 11 - 2 = 9. - For two trades, greedily locking in 2 -> 11 (+9) leaves only 3 -> 6 (+3) for 12, whereas splitting around the middle dip into 2 -> 9 (days 0 -> 1, +7) and 4 -> 11 (days 2 -> 3, +7) earns 7 + 7 = 14.

Example 2

Input:  prices = [12, 9, 7, 6, 3]
Output:
  profit_exactly_one(prices) -> -1
  profit_exactly_two(prices) -> -4

Explanation: - Because prices drop every day, every legal trade loses money. Buying on day 2 (7) and selling on day 3 (6) limits a single forced trade to -1. - Completing two non-overlapping trades on distinct days achieves at best (9 - 12) + (6 - 7) = -3 + (-1) = -4 using days (0, 1, 2, 3).

Example 3

Input:  prices = [8, 15, 10]
Output:
  profit_exactly_one(prices) -> 7
  profit_exactly_two(prices) -> None

Explanation: Buying on day 0 (8) and selling on day 1 (15) earns 7 for one trade, while 3 days cannot accommodate four strictly ordered indices buy1 < sell1 < buy2 < sell2.

Constraints

  • 0 <= len(prices) <= 10^5
  • Each prices[d] is an integer (positive, zero, or negative, with arbitrary Python integer precision).

Step-by-step walkthrough

  1. Understand the mandatory-trade rules and assumptions

    You are given prices, where prices[d] is the share price on day d. Unlike standard stock-trading problems where you can sit in cash and earn 0 during a downturn, here the trades are mandatory:

    • profit_exactly_one(prices): pick a buy day i and a strictly later sell day j (i < j) maximizing prices[j] - prices[i].
    • profit_exactly_two(prices): pick four strictly ordered days buy1 < sell1 < buy2 < sell2 maximizing (prices[sell1] - prices[buy1]) + (prices[sell2] - prices[buy2]).

    Pin down three modeling assumptions up front:

    1. One share at a time, zero fees, no short selling: you must purchase a share before selling it, and sell the first share before buying the second.
    2. Strictly distinct days (<, not <=): buying and selling on the same day would manufacture a fake 0 without market exposure, and sell1 < buy2 means two trades require at least 4 distinct days.
    3. Losses are permitted; impossible schedules return None: on [12, 9, 7, 6, 3], every valid trade loses money, and the smallest single-trade loss is 6 - 7 = -1. When len(prices) < 2 (for one trade) or len(prices) < 4 (for two trades), no legal schedule exists, so we return None to separate "impossible" from "traded and broke even at 0".
    Timeline for two mandatory trades (requires >= 4 days):
      day:   0 .... buy1 .... sell1 .... buy2 .... sell2 .... n-1
      rule:         buy1  <   sell1  <   buy2  <   sell2
      cash:   0  -> -p[buy1] -> +p[sell1] -> -p[buy2] -> +p[sell2]
    
  2. Start with brute force to verify the rules

    An exhaustive check tries every valid tuple of day indices:

    • One trade: check every pair (i, j) with 0 <= i < j < n (n * (n - 1) / 2 pairs -> O(n^2) time).
    • Two trades: check every quadruple (a, b, c, d) with 0 <= a < b < c < d < n (n * (n - 1) * (n - 2) * (n - 3) / 24 quadruples -> O(n^4) time).

    For n = 10 days, O(n^4) checks just 210 quadruples—ideal as a ground-truth oracle in unit tests! For n = 10,000 days, O(n^4) exceeds 4 * 10^14 operations. Let's turn both into single-pass O(n) scans using O(1) memory.

  3. One mandatory trade: pair each sell day with the cheapest earlier day

    If you sell on sell_day, the earlier day 0 .. sell_day - 1 maximizing prices[sell_day] - prices[buy_day] is always the day with the lowest price strictly before sell_day.

    Two details enforce the mandatory trade requirement:

    1. Seed best_profit with prices[1] - prices[0], never 0. Starting at 0 on [12, 9, 7] would return 0 (pretending zero trades happened) instead of -2.
    2. Score today's sell before updating cheapest_buy with today's price. Updating cheapest_buy first would subtract today's price from itself (0), buying and selling on the same day.
    Trace on Example 2: prices = [12, 9, 7, 6, 3]
      Start: cheapest_buy = 12, best_profit = 9 - 12 = -3
      sell_day = 1 (price 9): candidate = 9 - 12 = -3 -> best = -3; cheapest_buy = min(12, 9) = 9
      sell_day = 2 (price 7): candidate = 7 -  9 = -2 -> best = -2; cheapest_buy = min(9, 7)  = 7
      sell_day = 3 (price 6): candidate = 6 -  7 = -1 -> best = -1; cheapest_buy = min(7, 6)  = 6
      sell_day = 4 (price 3): candidate = 3 -  6 = -3 -> best = -1; cheapest_buy = min(6, 3)  = 3
      Result: -1
    
    from typing import List, Optional
    
    
    def profit_exactly_one(prices: List[int]) -> Optional[int]:
        # Need at least 2 distinct days (one to buy, a strictly later one to sell).
        if len(prices) < 2:
            return None
    
        # Seed best_profit with the first legal trade (buy day 0, sell day 1), NOT 0,
        # because 0 would secretly allow "skip trading" when all prices fall.
        best_profit = prices[1] - prices[0]
        # cheapest_buy tracks min(prices[0 .. sell_day - 1]), strictly before sell_day.
        cheapest_buy = prices[0]
    
        for sell_day in range(1, len(prices)):
            today_price = prices[sell_day]
            candidate_profit = today_price - cheapest_buy
            if candidate_profit > best_profit:
                best_profit = candidate_profit
    
            # Update cheapest_buy AFTER scoring today's sell so buy_day < sell_day holds
            # and we never buy and sell on the exact same day for a fake 0 profit.
            if today_price < cheapest_buy:
                cheapest_buy = today_price
    
        return best_profit
    
  4. Why a greedy "best single trade first" fails for two trades

    A tempting shortcut for two trades is: "Lock in the single best trade first, then find the best second trade in the leftover days." Watch how that fails on Example 1 (prices = [2, 9, 4, 11, 3, 6]):

    Index:   0   1   2    3   4   5
    Prices: [2,  9,  4,  11,  3,  6]
    
    Greedy pick:   buy day 0 (2) ----------> sell day 3 (11)  = +9
    Leftover:                                       buy 4 (3) -> sell 5 (6) = +3
    Greedy total = 9 + 3 = 12
    
    Optimal split: buy 0 (2) -> sell 1 (9)  AND  buy 2 (4) -> sell 3 (11)
    Optimal total = (9 - 2) + (11 - 4) = 7 + 7 = 14!
    

    Holding across the dip from 9 down to 4 captured +9 in one trade, whereas splitting into two trades around the dip captures +7 + +7 = +14. Because the two trades compete for days, we track all four stages together.

  5. Two mandatory trades: a four-stage wallet state machine

    Start your wallet at $0 cash. Every valid two-trade schedule passes through four ordered stages:

    1. after_buy1: bought the 1st share on day a -> wallet balance is -prices[a].
    2. after_sell1: sold the 1st share on day b > a -> wallet balance is after_buy1 + prices[b].
    3. after_buy2: bought the 2nd share on day c > b -> wallet balance is after_sell1 - prices[c].
    4. after_sell2: sold the 2nd share on day d > c -> wallet balance is after_buy2 + prices[d].

    Two rules guarantee mandatory execution on four distinct days:

    • Initialize all four balances to None ("not yet reachable"). after_sell1 cannot unlock until after_buy1 was set on an earlier day, preventing skipped trades and avoiding float("-inf") overflow on huge Python integers.
    • Update backward (after_sell2 -> after_buy2 -> after_sell1 -> after_buy1) each day. Updating after_sell2 before modifying after_buy2 ensures after_sell2 only reads after_buy2 from strictly earlier days.
    def _max_or_init(current_best: Optional[int], candidate: int) -> int:
        """Return candidate if this stage had not been reached yet, else max(current_best, candidate)."""
        if current_best is None or candidate > current_best:
            return candidate
        return current_best
    
    
    def profit_exactly_two(prices: List[int]) -> Optional[int]:
        if len(prices) < 4:
            return None
    
        after_buy1: Optional[int] = None
        after_sell1: Optional[int] = None
        after_buy2: Optional[int] = None
        after_sell2: Optional[int] = None
    
        for today_price in prices:
            # Update from stage 4 BACKWARD to stage 1 so each stage reads the
            # previous stage's balance from STRICTLY EARLIER days.
            if after_buy2 is not None:
                after_sell2 = _max_or_init(after_sell2, after_buy2 + today_price)
            if after_sell1 is not None:
                after_buy2 = _max_or_init(after_buy2, after_sell1 - today_price)
            if after_buy1 is not None:
                after_sell1 = _max_or_init(after_sell1, after_buy1 + today_price)
            after_buy1 = _max_or_init(after_buy1, -today_price)
    
        return after_sell2
    
  6. Trace Examples 1 and 2 day by day

    Watch one stage unlock on each of the first four days for Example 1 (prices = [2, 9, 4, 11, 3, 6]):

    Day  Price  after_buy1  after_sell1  after_buy2  after_sell2  What unlocked / improved?
    ---  -----  ----------  -----------  ----------  -----------  -------------------------------------
    0     2     -2          None         None        None         Bought 1st share at 2 (wallet: -2)
    1     9     -2           7           None        None         Sold 1st share at 9 (-2 + 9 = 7)
    2     4     -2           7            3          None         Bought 2nd share at 4 (7 - 4 = 3)
    3    11     -2           9            3           14          Sold 2nd share at 11 (3 + 11 = 14);
                                                                  also sell1 improved to -2 + 11 = 9
    4     3     -2           9            6           14          buy2 improved to 9 - 3 = 6
    5     6     -2           9            6           14          6 + 6 = 12 < 14, so 14 wins!
    

    Now trace strictly declining Example 2 (prices = [12, 9, 7, 6, 3]):

    Day  Price  after_buy1  after_sell1  after_buy2  after_sell2
    ---  -----  ----------  -----------  ----------  -----------
    0    12     -12         None         None        None
    1     9      -9          -3          None        None         (buy 12, sell 9 -> -3)
    2     7      -7          -2          -10         None         (sell1: -9+7=-2; buy2: -3-7=-10)
    3     6      -6          -1           -8          -4          (sell2: -10 + 6 = -4)
    4     3      -3          -1           -4          -4          (max(-4, -8 + 3) = -4)
    

    Even with falling prices, the DP finds (9 - 12) + (6 - 7) = -4.

  7. Complete solution

    from typing import List, Optional
    
    
    def profit_exactly_one(prices: List[int]) -> Optional[int]:
        """Best profit from exactly one trade: buy on day i, sell on a later day j > i.
    
        One share, no fees, no short selling. The result may be negative when
        prices never rise (the smallest possible loss). Returns None when fewer
        than 2 days are given, because no trade can be made.
        """
        # Need at least 2 distinct days (one to buy, a strictly later one to sell).
        if len(prices) < 2:
            return None
    
        # Seed best_profit with the first legal trade (buy day 0, sell day 1), NOT 0,
        # because 0 would secretly allow "skip trading" when all prices fall.
        best_profit = prices[1] - prices[0]
        # cheapest_buy tracks min(prices[0 .. sell_day - 1]), strictly before sell_day.
        cheapest_buy = prices[0]
    
        for sell_day in range(1, len(prices)):
            today_price = prices[sell_day]
            candidate_profit = today_price - cheapest_buy
            if candidate_profit > best_profit:
                best_profit = candidate_profit
    
            # Update cheapest_buy AFTER scoring today's sell so buy_day < sell_day holds
            # and we never buy and sell on the exact same day for a fake 0 profit.
            if today_price < cheapest_buy:
                cheapest_buy = today_price
    
        return best_profit
    
    
    def _max_or_init(current_best: Optional[int], candidate: int) -> int:
        """Return candidate if this stage had not been reached yet, else max(current_best, candidate)."""
        if current_best is None or candidate > current_best:
            return candidate
        return current_best
    
    
    def profit_exactly_two(prices: List[int]) -> Optional[int]:
        """Best total profit from exactly two trades on four distinct days.
    
        Days must satisfy buy1 < sell1 < buy2 < sell2 (you sell the first share
        before the day you buy the second). Losses are allowed when they are
        unavoidable. Returns None when fewer than 4 days are given.
        """
        # Four strictly ordered actions (buy1 < sell1 < buy2 < sell2) need >= 4 days.
        if len(prices) < 4:
            return None
    
        # Best wallet balance (in dollars, starting from 0) after finishing each stage
        # on some day seen so far. None means "not enough days have passed yet", which
        # prevents skipping trades and avoids float('-inf') overflow on huge ints.
        after_buy1: Optional[int] = None   # best of (-prices[a])
        after_sell1: Optional[int] = None  # best of (-prices[a] + prices[b])
        after_buy2: Optional[int] = None   # best of (-prices[a] + prices[b] - prices[c])
        after_sell2: Optional[int] = None  # best of (-prices[a] + prices[b] - prices[c] + prices[d])
    
        for today_price in prices:
            # Update from stage 4 BACKWARD to stage 1. That way, each stage reads the
            # previous stage's balance from STRICTLY EARLIER days, guaranteeing
            # buy1 < sell1 < buy2 < sell2 with no two actions sharing today.
            if after_buy2 is not None:
                after_sell2 = _max_or_init(after_sell2, after_buy2 + today_price)
            if after_sell1 is not None:
                after_buy2 = _max_or_init(after_buy2, after_sell1 - today_price)
            if after_buy1 is not None:
                after_sell1 = _max_or_init(after_sell1, after_buy1 + today_price)
            after_buy1 = _max_or_init(after_buy1, -today_price)
    
        return after_sell2
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a four-step relay race for your wallet, starting at $0: Buy 1 -> Sell 1 -> Buy 2 -> Sell 2. Buying a share subtracts today's stock price from your wallet, and selling adds today's price back. Instead of remembering which specific days we picked, dynamic programming (solving a sequence problem by keeping only the best result for each stage seen so far) lets us carry just four numbers from left to right: the highest wallet balance achievable after finishing stage 1, stage 2, stage 3, and stage 4 on the days scanned so far.

Two naive ideas fail right away. First, checking every (buy1, sell1, buy2, sell2) quadruple takes O(n^4) time, and a greedy choice (locking in the single biggest trade first and taking whatever is left) fails on [2, 9, 4, 11, 3, 6] because 2 -> 11 (+9) plus 3 -> 6 (+3) earns 12, missing 2 -> 9 (+7) plus 4 -> 11 (+7) = 14. Second, initializing best profits to 0 (as in the standard "at most two trades" problem) silently lets the algorithm skip trading when prices fall, whereas initializing unreachable stages to a sentinel value (None, a special marker meaning "this stage has not happened yet") forces every buy and sell to occur on distinct days even if the total is negative.

Trace four falling days prices = [12, 9, 7, 6] to watch both rules work together:

  1. Day 0 (price = 12): Only stage 1 can happen, so after_buy1 = -12, while after_sell1, after_buy2, and after_sell2 stay None.
  2. Day 1 (price = 9): Updating backward so each stage only reads earlier days, after_sell1 becomes -12 + 9 = -3 (one mandatory trade loses 3), and after_buy1 improves to -9.
  3. Day 2 (price = 7): after_buy2 unlocks as after_sell1 - 7 = -3 - 7 = -10, after_sell1 improves to max(-3, -9 + 7) = -2, and after_buy1 improves to -7.
  4. Day 3 (price = 6): after_sell2 finally unlocks as after_buy2 + 6 = -10 + 6 = -4, returning the least possible two-trade loss of -4 (12 -> 9 and 7 -> 6).

Complexity

  • Time: Both profit_exactly_one and profit_exactly_two run in O(n) time, where n is len(prices), because each function scans the price list once from left to right and performs a fixed, constant number of comparisons and additions (O(1) work) per day.
  • Space: Both functions use O(1) auxiliary space because profit_exactly_one stores only two integers (best_profit and cheapest_buy) and profit_exactly_two stores only four stage balances (after_buy1, after_sell1, after_buy2, after_sell2), regardless of how long prices is.

Edge cases

  • Fewer days than required (n < 2 for one trade, n < 4 for two trades): no valid set of distinct days exists ([8, 15, 10] returns None for two trades), distinguishing impossible schedules from break-even 0 trades.
  • Minimum valid length (n = 2 or n = 4): every day's role is forced; [2, 7, 3, 10] has only one two-trade schedule (7 - 2) + (10 - 3) = 12.
  • Strictly decreasing prices: trades remain mandatory, so answers are negative ([12, 9, 7, 6, 3] returns -1 for one trade and -4 for two trades).
  • All equal prices: [6, 6] returns 0 and [5, 5, 5, 5] returns 0—real trades that broke even.
  • One steady climb: [2, 4, 6, 8, 10] earns 10 - 2 = 8 with one trade, but at most 6 with two trades (for example (4 - 2) + (10 - 6) = 6) because sell1 < buy2 forbids selling and rebuying on the same day.
  • Arbitrarily large integers: keeping uninitialized states as None rather than float("-inf") avoids OverflowError when Python integers exceed the 64-bit float range (~1.8 * 10^308).

Common mistakes

  • Initializing best_profit or sell states to 0: 0 represents "doing zero trades", which turns a forced-loss input like [12, 9, 7, 6, 3] into a wrong answer of 0 instead of -1.
  • Updating cheapest_buy before computing today_price - cheapest_buy: doing so lets buy_day == sell_day, producing a fake 0 profit on strictly falling prices.
  • Updating the four states in forward order (buy1 -> sell1 -> buy2 -> sell2): if after_sell1 reads today's updated after_buy1, a single day can be used for multiple actions, violating buy1 < sell1 < buy2 < sell2.
  • Picking the best single trade greedily and searching the remainder: this misses higher combined profits achieved by splitting one long rise around a middle dip, such as [2, 9, 4, 11, 3, 6].
  • Returning 0 when len(prices) is too short: callers cannot tell whether the best trade broke even ([6, 6] -> 0) or no trade was possible ([6] -> None).

Alternative approaches

  • Prefix and suffix arrays (O(n) time, O(n) space): Precompute best_prefix[k] = best single mandatory trade in prices[0 .. k] (for k >= 1) and best_suffix[k] = best single mandatory trade in prices[k .. n - 1] (for k <= n - 2), then take the maximum of best_prefix[k] + best_suffix[k + 1] over all split points 1 <= k <= n - 3. This clearly illustrates why two non-overlapping trades partition the timeline at some index k, though it allocates two O(n) arrays instead of four scalar variables.
  • Exhaustive day combinations (O(n^2) and O(n^4) time, O(1) space): Enumerate all index pairs i < j or quadruples a < b < c < d. Too slow for large n, but ideal in unit tests to cross-check random small arrays.

Follow-up questions

  • How does the algorithm change if selling the first share and buying the second share on the same day is permitted (buy1 < sell1 <= buy2 < sell2)? First, the minimum length drops from 4 days to 3 days (since sell1 and buy2 may share the middle day). Second, inside the per-day loop, update in the order after_sell2, then after_sell1, then after_buy2 (reading today's newly updated after_sell1), and finally after_buy1; selling and immediately rebuying at the same price cancels out, so [2, 4, 6, 8, 10] now earns 8 instead of 6.
  • How can you extend the state machine to enforce k mandatory non-overlapping trades? Require len(prices) >= 2 * k and maintain two lists after_buy[1 .. k] and after_sell[1 .. k] initialized to None (with after_sell[0] = 0 representing the $0 starting wallet before trade 1). For each price, loop t backward from k down to 1, updating after_sell[t] from after_buy[t] + price and then after_buy[t] from after_sell[t - 1] - price; this runs in O(n * k) time and O(k) space.
  • How would you recover the exact buy and sell day indices that achieve the optimal total? Store a (balance, days_tuple) pair for each stage instead of just the integer balance—for example, after_sell1 stores (7, (0, 1)) meaning profit 7 from buying on day 0 and selling on day 1. Whenever a candidate strictly improves a stage's balance on day d, carry the previous stage's days_tuple + (d,) forward; after_sell2 ends with both the optimal profit and the exact four indices (buy1, sell1, buy2, sell2) in O(n) time and O(1) space.

Follow-up questions

Similar questions

More Retool interview questions

All 2 Retool questions →