Best Time to Buy and Sell Stock

Find the maximum profit from buying and selling a stock once.

Pattern

Sliding Window Min

This problem follows the Sliding Window Min pattern, commonly found in the Sliding Window category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Track minimum price seen so far. At each price, calculate profit from min.

Key Insight

You only need to track the minimum price seen so far — at each day, the best you could do is sell at today's price minus that minimum.

Step-by-step

  1. 1Initialize minPrice to infinity and maxProfit to 0
  2. 2Iterate through each price
  3. 3Update minPrice if current price is lower
  4. 4Calculate profit = price - minPrice, update maxProfit if larger
  5. 5Return maxProfit

Pseudocode

minPrice = infinity
maxProfit = 0
for price in prices:
    minPrice = min(minPrice, price)
    maxProfit = max(maxProfit, price - minPrice)
return maxProfit
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(1)
More Sliding Window Problems

Master this pattern with YeetCode

Practice Best Time to Buy and Sell Stock and similar Sliding Window problems with flashcards. Build pattern recognition through active recall.

Practice this problem