title: Best Time to Buy and Sell Stock slug: best-time-to-buy-and-sell-stock difficulty: easy leetcode_id: 121 leetcode_url: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ categories: - arrays - dynamic-programming patterns: - greedy description: | You are given an array `prices` where `prices[i]` is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. constraints: | - 1 <= prices.length <= 10^5 - 0 <= prices[i] <= 10^4 examples: - input: "prices = [7,1,5,3,6,4]" output: "5" explanation: "Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5." - input: "prices = [7,6,4,3,1]" output: "0" explanation: "No profitable transaction possible." explanation: approach: | 1. Track the minimum price seen so far 2. For each day, calculate the profit if we sold today 3. Update maximum profit if current profit is higher 4. Update minimum price if current price is lower intuition: | To maximize profit, we want to buy at the lowest price and sell at the highest price after that. Rather than comparing all pairs (O(n²)), we track the minimum price seen so far. For each day, we ask: "If I sold today, what's the maximum profit?" This is simply today's price minus the minimum price we've seen before today. common_pitfalls: - title: Selling before buying description: | Ensure you only consider selling on days after the minimum price was observed. Tracking minimum as you iterate handles this automatically. wrong_approach: "Using global min and max without considering order" correct_approach: "Track running minimum, calculate profit from that point" - title: Initializing min_price to 0 description: | Initialize min_price to the first element or infinity, not 0, since prices are positive and you need to track actual minimum. key_takeaways: - Single pass through array is sufficient - Track running minimum for optimal buy point - Greedy approach works when you can only make one transaction - This is a foundation for more complex stock problems time_complexity: "O(n)" space_complexity: "O(1)" complexity_explanation: | Time: Single pass through the prices array. Space: Only two variables needed (min_price, max_profit). solutions: - approach_name: Single Pass (Optimal) is_optimal: true code: | def max_profit(prices: list[int]) -> int: min_price = float('inf') max_profit = 0 for price in prices: if price < min_price: min_price = price elif price - min_price > max_profit: max_profit = price - min_price return max_profit explanation: | Track minimum price seen so far and maximum profit achievable. Update both as we iterate through prices.