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
1share 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 most1share at any time). profit_exactly_one(prices): Select indices0 <= buy < sell < len(prices)maximizingprices[sell] - prices[buy]. Even if share prices fall every single day, the trade is still required—return the smallest possible loss (a negative integer). ReturnNonewhenlen(prices) < 2.profit_exactly_two(prices): Select four strictly increasing indices0 <= 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. ReturnNonewhenlen(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
Understand the mandatory-trade rules and assumptions
You are given
prices, whereprices[d]is the share price on dayd. Unlike standard stock-trading problems where you can sit in cash and earn0during a downturn, here the trades are mandatory:profit_exactly_one(prices): pick a buy dayiand a strictly later sell dayj(i < j) maximizingprices[j] - prices[i].profit_exactly_two(prices): pick four strictly ordered daysbuy1 < sell1 < buy2 < sell2maximizing(prices[sell1] - prices[buy1]) + (prices[sell2] - prices[buy2]).
Pin down three modeling assumptions up front:
- 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.
- Strictly distinct days (
<, not<=): buying and selling on the same day would manufacture a fake0without market exposure, andsell1 < buy2means two trades require at least 4 distinct days. - Losses are permitted; impossible schedules return
None: on[12, 9, 7, 6, 3], every valid trade loses money, and the smallest single-trade loss is6 - 7 = -1. Whenlen(prices) < 2(for one trade) orlen(prices) < 4(for two trades), no legal schedule exists, so we returnNoneto 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]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)with0 <= i < j < n(n * (n - 1) / 2pairs ->O(n^2)time). - Two trades: check every quadruple
(a, b, c, d)with0 <= a < b < c < d < n(n * (n - 1) * (n - 2) * (n - 3) / 24quadruples ->O(n^4)time).
For
n = 10days,O(n^4)checks just210quadruples—ideal as a ground-truth oracle in unit tests! Forn = 10,000days,O(n^4)exceeds4 * 10^14operations. Let's turn both into single-passO(n)scans usingO(1)memory.- One trade: check every pair
One mandatory trade: pair each sell day with the cheapest earlier day
If you sell on
sell_day, the earlier day0 .. sell_day - 1maximizingprices[sell_day] - prices[buy_day]is always the day with the lowest price strictly beforesell_day.Two details enforce the mandatory trade requirement:
- Seed
best_profitwithprices[1] - prices[0], never0. Starting at0on[12, 9, 7]would return0(pretending zero trades happened) instead of-2. - Score today's sell before updating
cheapest_buywith today's price. Updatingcheapest_buyfirst 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: -1from 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- Seed
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
9down to4captured+9in 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.Two mandatory trades: a four-stage wallet state machine
Start your wallet at
$0cash. Every valid two-trade schedule passes through four ordered stages:after_buy1: bought the 1st share on daya-> wallet balance is-prices[a].after_sell1: sold the 1st share on dayb > a-> wallet balance isafter_buy1 + prices[b].after_buy2: bought the 2nd share on dayc > b-> wallet balance isafter_sell1 - prices[c].after_sell2: sold the 2nd share on dayd > c-> wallet balance isafter_buy2 + prices[d].
Two rules guarantee mandatory execution on four distinct days:
- Initialize all four balances to
None("not yet reachable").after_sell1cannot unlock untilafter_buy1was set on an earlier day, preventing skipped trades and avoidingfloat("-inf")overflow on huge Python integers. - Update backward (
after_sell2->after_buy2->after_sell1->after_buy1) each day. Updatingafter_sell2before modifyingafter_buy2ensuresafter_sell2only readsafter_buy2from 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_sell2Trace 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.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:
- Day 0 (
price = 12): Only stage 1 can happen, soafter_buy1 = -12, whileafter_sell1,after_buy2, andafter_sell2stayNone. - Day 1 (
price = 9): Updating backward so each stage only reads earlier days,after_sell1becomes-12 + 9 = -3(one mandatory trade loses3), andafter_buy1improves to-9. - Day 2 (
price = 7):after_buy2unlocks asafter_sell1 - 7 = -3 - 7 = -10,after_sell1improves tomax(-3, -9 + 7) = -2, andafter_buy1improves to-7. - Day 3 (
price = 6):after_sell2finally unlocks asafter_buy2 + 6 = -10 + 6 = -4, returning the least possible two-trade loss of-4(12 -> 9and7 -> 6).
Complexity
- Time: Both
profit_exactly_oneandprofit_exactly_tworun inO(n)time, wherenislen(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 becauseprofit_exactly_onestores only two integers (best_profitandcheapest_buy) andprofit_exactly_twostores only four stage balances (after_buy1,after_sell1,after_buy2,after_sell2), regardless of how longpricesis.
Edge cases
- Fewer days than required (
n < 2for one trade,n < 4for two trades): no valid set of distinct days exists ([8, 15, 10]returnsNonefor two trades), distinguishing impossible schedules from break-even0trades. - Minimum valid length (
n = 2orn = 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-1for one trade and-4for two trades). - All equal prices:
[6, 6]returns0and[5, 5, 5, 5]returns0—real trades that broke even. - One steady climb:
[2, 4, 6, 8, 10]earns10 - 2 = 8with one trade, but at most6with two trades (for example(4 - 2) + (10 - 6) = 6) becausesell1 < buy2forbids selling and rebuying on the same day. - Arbitrarily large integers: keeping uninitialized states as
Nonerather thanfloat("-inf")avoidsOverflowErrorwhen Python integers exceed the 64-bit float range (~1.8 * 10^308).
Common mistakes
- Initializing
best_profitor sell states to0:0represents "doing zero trades", which turns a forced-loss input like[12, 9, 7, 6, 3]into a wrong answer of0instead of-1. - Updating
cheapest_buybefore computingtoday_price - cheapest_buy: doing so letsbuy_day == sell_day, producing a fake0profit on strictly falling prices. - Updating the four states in forward order (
buy1->sell1->buy2->sell2): ifafter_sell1reads today's updatedafter_buy1, a single day can be used for multiple actions, violatingbuy1 < 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
0whenlen(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): Precomputebest_prefix[k]= best single mandatory trade inprices[0 .. k](fork >= 1) andbest_suffix[k]= best single mandatory trade inprices[k .. n - 1](fork <= n - 2), then take the maximum ofbest_prefix[k] + best_suffix[k + 1]over all split points1 <= k <= n - 3. This clearly illustrates why two non-overlapping trades partition the timeline at some indexk, though it allocates twoO(n)arrays instead of four scalar variables. - Exhaustive day combinations (
O(n^2)andO(n^4)time,O(1)space): Enumerate all index pairsi < jor quadruplesa < b < c < d. Too slow for largen, 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
4days to3days (sincesell1andbuy2may share the middle day). Second, inside the per-day loop, update in the orderafter_sell2, thenafter_sell1, thenafter_buy2(reading today's newly updatedafter_sell1), and finallyafter_buy1; selling and immediately rebuying at the same price cancels out, so[2, 4, 6, 8, 10]now earns8instead of6. - How can you extend the state machine to enforce k mandatory non-overlapping trades? Require
len(prices) >= 2 * kand maintain two listsafter_buy[1 .. k]andafter_sell[1 .. k]initialized toNone(withafter_sell[0] = 0representing the$0starting wallet before trade 1). For each price, looptbackward fromkdown to1, updatingafter_sell[t]fromafter_buy[t] + priceand thenafter_buy[t]fromafter_sell[t - 1] - price; this runs inO(n * k)time andO(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_sell1stores(7, (0, 1))meaning profit7from buying on day0and selling on day1. Whenever a candidate strictly improves a stage's balance on dayd, carry the previous stage'sdays_tuple + (d,)forward;after_sell2ends with both the optimal profit and the exact four indices(buy1, sell1, buy2, sell2)inO(n)time andO(1)space.
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)?
- How can you extend the state machine to enforce k mandatory non-overlapping trades?
- How would you recover the exact buy and sell day indices that achieve the optimal total?
Similar questions
- Vehicle Rental Relational Schema and Booking APIs
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One