💡
Exercise 12

Best Time to Buy Stock 20 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

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:

prices = [7, 1, 5, 3, 6, 4] # Buy on day 2 (price = 1) # Sell on day 5 (price = 6) # Profit = 6 - 1 = 5 ←— maximum profit!

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:

  • Day 1: price=7, min=7, profit=0, best=0
  • Day 2: price=1, min=1, profit=0, best=0
  • Day 3: price=5, min=1, profit=4, best=4
  • Day 4: price=3, min=1, profit=2, best=4
  • Day 5: price=6, min=1, profit=5, best=5
  • Day 6: price=4, min=1, profit=3, best=5

Complexity: Time O(n) — one pass through the array. Space O(1) — just two variables.

📋 Instructions
Implement `maxProfit(prices)` that returns the maximum profit from buying and selling a stock once. - You must buy before you sell - If no profit is possible, return 0 - Use the single-pass approach with O(1) space
One pass: Track min_price seen so far. At each price, calculate profit = price - min_price. Track max_profit. Don't overthink it — just one loop!
⚠️ Try solving it yourself first — you'll learn more!
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
🧪 Test Cases
Input
maxProfit([7, 1, 5, 3, 6, 4])
Expected
5
Test case 1
Input
maxProfit([7, 6, 4, 3, 1])
Expected
0
Boundary value
Input
maxProfit([2, 4, 1])
Expected
2
Test case 3
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.