Best Time to Buy and Sell Stock
LeetCode 121 • Easy • Single Transaction
Buy one day, sell on a later day. Maximize profit = sell_price − buy_price. Track min_price so far; best profit if sold today = price − min_price.
TimeO(n)single pass
SpaceO(1)two variables
Day: —
Min: —
Max: —
Ready
Press Play. For each day: update min_price = min(min_price, price); profit = price − min_price; max_profit = max(max_profit, profit).
TimeO(n)single pass
SpaceO(n)call stack
Recursive: helper(i, min_so_far) — base when i ≥ n return 0; profit = prices[i] − min_so_far; new_min = min(min_so_far, prices[i]); return max(profit, helper(i+1, new_min)).
3
Practice until you don't need to look. Use the guide comments below as scaffolding. The green highlights are the nuances to burn into memory.
PATTERN ▸ Track min so far; profit = price − min_price O(n) · O(1)
① INIT
min_price = float('inf')
max_profit = 0
② LOOP
for price in prices:
③ UPDATE MIN & PROFIT
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
④ RETURN
return max_profit
▼ your implementation ▼
Verify your solution: