Problem · LC 121

Best Time to Buy and Sell Stock

Easy
◧ Foundation · single pass with min tracking→ Min Tracking

How to recognize it

An array of stock prices. You can buy once and sell once (buy must come before sell). Find the max profit. Signal: "buy and sell", "max profit", or a single pass over prices.

The core idea

Track the minimum price seen so far. For each price, calculate profit (current - min). Update the global max profit. This is a sliding window edge case: the window collapses to "best min so far".

Why It's Tricky

It's not about comparing adjacent prices. You need the MINIMUM price BEFORE the current price, which requires tracking state across the entire array.

The Key Insight

Keep a running minimum price. At each step, profit = current_price - min_so_far. The "window" degenerates to a single point (the min), but the logic is the same: what's the best return from any earlier point?

Step-by-Step Walkthrough

Example: [7,1,5,3,6,4]

Price 7: min=7, profit=0
Price 1: min=1, profit=0
Price 5: min=1, profit=4
Price 3: min=1, profit=2
Price 6: min=1, profit=5
Price 4: min=1, profit=3

Max profit: 5 (buy at 1, sell at 6)

time O(n)
space O(1)
best_time_to_buy_and_sell_stock
def maxProfit(prices):
    if not prices:
        return 0
    min_price = prices[0]
    max_profit = 0
    for price in prices[1:]:
        profit = price - min_price
        max_profit = max(max_profit, profit)
        min_price = min(min_price, price)
    return max_profit

Interview gotchas

  • Don't compare adjacent prices — you need the global minimum.
  • Profit can be zero if prices only decrease.
  • Edge case: array of length 1 → no transaction possible → profit = 0.

💡 What to Say in the Interview

  • Say: "I'll track the minimum price and compute max profit on the fly."
  • Explain: "At each price, profit = current - min_so_far. Update both max profit and the min."
  • State: "O(n) time, O(1) space — single pass, constant extra space."
  • Note: "Edge case: if prices only decrease, profit is 0."

Variants they'll pivot to

Solve the base problem, then interviewers escalate. These are the usual next steps — knowing the connection is worth more than memorizing each.