Skip to main content

Best Time to Buy and Sell Stock - LeetCode 121 Solution

·320 words·2 mins

Problem Overview
#

The Best Time to Buy and Sell Stock problem from LeetCode asks you to find the maximum profit from a single buy-sell transaction.

Problem Statement: You are given an array prices where prices[i] is the price of a given stock on the i-th day. You want to maximize your profit by choosing a single day to buy one stock and 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.

Example:

  • Input: prices = [7,1,5,3,6,4]

  • Output: 5 (buy at 1, sell at 6)

  • Input: prices = [7,6,4,3,1]

  • Output: 0 (no profit possible)

  • Input: prices = [2,4,1]

  • Output: 2 (buy at 2, sell at 4)

Solution Approach
#

C# Solution - Single Pass with Min Tracking
#

The optimal approach using a single pass to track minimum price and maximum profit:

public class Solution {
    public int MaxProfit(int[] prices) {
        var minPrice = prices[0];
        var maxProfit = 0;

        for(int i = 0; i < prices.Length; i++) {
            if(prices[i] < minPrice) {
                minPrice = prices[i];
            }else{
                var profit = prices[i] - minPrice;
                if(profit > maxProfit) {
                    maxProfit = profit;
                }
            }
        }

        return maxProfit;
    }
}

Time Complexity: O(n) - single pass through prices array Space Complexity: O(1) - only constant extra space

Key Insights
#

  1. Memory: Track the minimum price seen so far
  2. Greedy Approach: At each price, calculate profit if we sell at that price
  3. Single Pass: Optimal solution requires only one iteration
  4. Constraint: Must sell after buying (future day requirement)

Related Problems#

  • Best Time to Buy and Sell Stock II (multiple transactions)
  • Best Time to Buy and Sell Stock III (at most 2 transactions)
  • Best Time to Buy and Sell Stock IV (at most k transactions)

Video Tutorial
#

Watch the complete explanation and walkthrough in the video above for a detailed solution approach and implementation details.