Skip to content
mlmentorship

Best Time to Buy and Sell Stock

Summarize the cheapest eligible baseline for each sale, preserve optional profit, and change update timing for witnesses and mandatory trades.

Published · 13 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Best Time to Buy and Sell Stock

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A list of finite integer prices in chronological day order. Output. Return the largest achievable sale price minus purchase price, or zero if no profitable trade exists. Rules. Buy at most once and sell on a strictly later day. There are no fees, short sales, or multiple transactions. Doing nothing is allowed. Empty and singleton lists return zero; leave the list unchanged. Example. For prices [7, 1, 5, 3, 6, 4], return 5. Buy at index 1 for 1 and sell at index 4 for 6. For falling prices [7, 6, 4], return 0, not a negative forced-trade profit.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

For each possible selling day, subtract the lowest price in its scanned prefix and preserve the largest profit.

Problem trace

Each selling day uses its cheapest earlier eligible price

Input and goalBuy once, then sell later. Return the largest profit.
Initialize from infinityDay 0 sets lowest=min(infinity,7)=7. Its same-day zero cannot improve the no-trade best=0.
lowday701152336445
scannedPrefix[0..0]arithmeticlowest=7; profit=7-7=0; best=0
low
0
day
0
scanned prefix
[0..0]

Recognize it
Use a running minimum when an ordered one-pass problem asks for the best later-minus-earlier difference and the buy or baseline must occur before the current item.
Keep true
After each day, lowest is the minimum price in the scanned prefix and best is the largest valid sell-minus-earlier-buy profit whose selling day lies in that prefix.
Reuse it
For maximum ordered differences, summarize the best earlier baseline while treating each new value as the right endpoint; analogous scans find maximum rise, minimum spread, and best prefix-relative gain.
Day 0 sets lowest=min(infinity,7)=7. Its same-day zero cannot improve the no-trade best=0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is day 4 still the winning sell day when the cursor has reached day 5?
Full interview answer 13 min read

Choose at most one purchase and a later sale to maximize the profit from a daily price list.

Problem

Input. A list of finite integer prices in chronological day order.

Output. Return the largest achievable sale price minus purchase price, or zero if no profitable trade exists.

Rules. Buy at most once and sell on a strictly later day. There are no fees, short sales, or multiple transactions. Doing nothing is allowed. Empty and singleton lists return zero; leave the list unchanged.

Example. For prices [7, 1, 5, 3, 6, 4], return 5. Buy at index 1 for 1 and sell at index 4 for 6. For falling prices [7, 6, 4], return 0, not a negative forced-trade profit.

Picture

Scan [7,1,5,3,6,4] from left to right:

DayPricelowest after insertionCandidatebest
07700
11100
25144
33124
46155
54135

For one fixed sale, a cheaper buy cannot reduce profit.

After each day, lowest stores the prefix minimum. The saved best stores the largest completed optional profit.

The source inserts today’s price before computing price - lowest. A new minimum produces a same-day zero, not a valid transaction.

That zero cannot improve best, which starts at zero. Every positive improvement uses a strictly earlier, lower price.

The result is five: buy on day one and sell on day four. The later price four does not erase that saved answer.

Visual low marks the current prefix minimum’s day; day marks the current candidate sale. The underline marks the saved trade, not today’s candidate.

Problem trace

Separate example: a worse current trade does not erase the saved best

Worked example: the saved trade survives a worse current selling dayPrices (3,1,5,2) produce best profit 4 at price 5. The final price gives current profit 1 but does not erase the saved 4.A worse selling day does not erasethe best completed tradeInput order: 3, 1, 5, 2Blue: current; green: saved best123440Checkpoint numberCurrent: 0, 0, 4, 1Saved: 0, 0, 4, 4
Read it this way: Prices (3,1,5,2) produce best profit 4 at price 5. The final price gives current profit 1 but does not erase the saved 4. Does the final selling price two remove the earlier opportunity to buy at one and sell at five?
Reference drawing

Problem trace

Keep the best earlier trade even when the current day is worse

Worked example: the saved trade survives a worse current selling dayPrices (3,1,5,2) produce best profit 4 at price 5. The final price gives current profit 1 but does not erase the saved 4.A worse selling day does not erasethe best completed tradeInput order: 3, 1, 5, 2Blue: current; green: saved best123440Checkpoint numberCurrent: 0, 0, 4, 1Saved: 0, 0, 4, 4
Execution trace
Input and goalBuy once, then sell later. Return the largest profit.
Initialize from infinityDay 0 sets lowest=min(infinity,7)=7. Its same-day zero cannot improve the no-trade best=0.
lowday701152336445
scannedPrefix[0..0]arithmeticlowest=7; profit=7-7=0; best=0
low
0
day
0
scanned prefix
[0..0]

Recognize it
Use a running minimum when an ordered one-pass problem asks for the best later-minus-earlier difference and the buy or baseline must occur before the current item.
Keep true
After each day, lowest is the minimum price in the scanned prefix and best is the largest valid sell-minus-earlier-buy profit whose selling day lies in that prefix.
Reuse it
For maximum ordered differences, summarize the best earlier baseline while treating each new value as the right endpoint; analogous scans find maximum rise, minimum spread, and best prefix-relative gain.
Day 0 sets lowest=min(infinity,7)=7. Its same-day zero cannot improve the no-trade best=0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is day 4 still the winning sell day when the cursor has reached day 5?
Read it this way: Prices (3,1,5,2) produce best profit 4 at price 5. The final price gives current profit 1 but does not erase the saved 4. Does the final selling price two remove the earlier opportunity to buy at one and sell at five?

Code

def max_profit(prices: list[int]) -> int:
   lowest = float("inf")
   best = 0

   for price in prices:
      lowest = min(lowest, price)
      best = max(best, price - lowest)
   return best

For days, the scan uses integer operations and stored slots. Global maximum minus global minimum fails on [7,1]: the earlier seven cannot be a later sale.

Change the Saved Result or Obligation

Start from max_profit. Two adjustable parts are the returned evidence and permission to skip trading.

  1. Return a feasible witness.

    New task: Return [profit, buy, sell] for a profitable trade, or None.

    Picture and change: Retain the minimum’s index. Score each sale against the strictly earlier minimum before inserting today’s price.

    Code: Complete replacement:

    def best_trade_days(prices):
       if len(prices) < 2:
          return None
       lowest, buy = prices[0], 0
       best, result = 0, None
       for sell in range(1, len(prices)):
          profit = prices[sell] - lowest
          if profit > best:
             best, result = profit, [profit, buy, sell]
          if prices[sell] < lowest:
             lowest, buy = prices[sell], sell
       return result

    Check: [7,1,5,3,6,4] returns [5,1,4]; [3,2,1] returns None.

    Strict comparisons retain the earliest sale attaining the best profit and its earliest minimum-price buy. Time remains , with slots.

    Use when: The caller needs actual, strictly ordered days rather than a scalar optimum.

  2. Require exactly one trade.

    New task: Return the best profit even when every possible trade loses money.

    Picture and change: Remove no-trade zero. Initialize best from the first valid pair and score before updating lowest.

    Code: Complete replacement; fewer than two days returns None.

    def mandatory_trade_profit(prices):
       if len(prices) < 2:
          return None
       lowest, best = prices[0], prices[1] - prices[0]
       for sell in range(1, len(prices)):
          best = max(best, prices[sell] - lowest)
          lowest = min(lowest, prices[sell])
       return best

    Check: [7,5,1] returns -2, while the optional reference returns zero. A singleton returns None.

    Inserting the current day first would introduce an illegal same-day zero. Initializing best = 0 would also hide every loss.

    Use when: Skipping the action is forbidden. Time remains , with slots.

Rebuild Eligibility

How would a minimum waiting period change the stored minimum?

Answer: Admit a buy day only when it is old enough for the current sale. The minimum’s role stays unchanged.

Multiple trades, fees, cooldowns, and short selling need separately derived state. This deterministic array task makes no market forecast.