This is LeetCode #121: Best Time to Buy and Sell Stock — one of the top 5 most asked interview questions!
💡 Think of it like this: Imagine you have a time machine, and you can see stock prices for every day. You want to buy on the cheapest day and sell on the most expensive day AFTER that. What's the maximum profit you can make?
Example:
The trick: As you go through each day, keep track of the lowest price so far. At each day, check: if I sell today, what's my profit?
💭 Go for it! Apply the approach above in your own code. If you get stuck, use the hint below! 🔥
Step-by-step trace:
Complexity: Time O(n) — one pass through the array. Space O(1) — just two variables.
def maxProfit(prices):
min_price = float('inf') # Start with infinity
max_profit = 0
for price in prices:
min_price = min(min_price, price) # Update lowest price
profit = price - min_price # If I sell today
max_profit = max(max_profit, profit) # Best profit so far
return max_profit
maxProfit([7, 1, 5, 3, 6, 4])
5
maxProfit([7, 6, 4, 3, 1])
0
maxProfit([2, 4, 1])
2