Easy
Best Time to Buy/Sell Stock
👶 The 5-Year-Old Summary
Buy low, sell high! One buy, one sell. [7,1,5,3,6,4] → buy at 1, sell at 6 = profit 5!
🎮 Interactive Visualizer
prices = [7, 1, 5, 3, 6, 4]
🧠The Brain Hack
Track minimum price so far! At each day, profit = current price - min price so far. Keep the max profit. This is like a sliding window of time!
💻 The Clean Solution
def max_profit(prices):
min_price = float('inf')
max_profit = 0
for price in prices:
# Update minimum price
if price < min_price:
min_price = price
# Calculate profit if sold today
else:
profit = price - min_price
max_profit = max(max_profit, profit)
return max_profit
# [7,1,5,3,6,4] → 5 (buy at 1, sell at 6)
Time: O(n)
Space: O(1)