Best Time to Buy and Sell Stock

Find maximum profit from buying and selling stock once.

Easy

Examples

Example 1: [7,1,5,3,6,4] → 5 (buy at 1, sell at 6)

Implementation

Ruby

  # 🟩 Best Time to Buy and Sell Stock
  #
  # Input Examples:
  #   max_profit([7, 1, 5, 3, 6, 4]) => 5  # Buy at 1, sell at 6
  #   max_profit([7, 6, 4, 3, 1]) => 0     # No profit possible
  #
  # Time Complexity: O(n)
  def max_profit(prices)
    min_price = Float::INFINITY
    max_profit = 0

    prices.each_with_index do |price, i|
      if price < min_price
        min_price = price
        puts "Day #{i}: New min price = #{min_price}"
      else
        profit = price - min_price
        max_profit = [ max_profit, profit ].max
        puts "Day #{i}: Current price = #{price}, Profit if sold = #{profit}, Max Profit = #{max_profit}"
      end
    end

    puts "Final max profit: #{max_profit}"
    max_profit

Complexity Analysis

Time Complexity: O(n)
Space Complexity: O(1)

Patterns & Techniques

Problem Details

Category: Pointer And Sliding Window
Difficulty: Easy
Module: PointerAndSlidingWindow
Method: max_profit
← Back to Pointer And Sliding Window