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.
# ─── BEST TIME BUY SELL (LeetCode 121) ───
# Pattern: Track min so far; profit today = price − min_price
# Time: O(n) Space: O(1)
#
# 1. Define: maxProfit(prices)
#
# 2. Init: min_price = float('inf'); max_profit = 0
#
# 3. Loop: for price in prices:
#
# 4. Update min: min_price = min(min_price, price)
# 5. Track best: max_profit = max(max_profit, price - min_price)
#
# 6. Return: return max_profit
#
# Vars: min_price, max_profit, price
▼ your implementation ▼
Verify your solution: