Greedy Algorithms
Easy

Best Time to Buy and Sell Stock

Maximize profit by choosing a single day to buy and a different day in the future to sell.
Problem Understanding

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 choosing a different day in the future to sell that stock.

Return the maximum profit. If no profit possible, return 0.

Strategy

We can iterate through the prices and keep track of:

  1. Min Price So Far: The lowest price we've seen to buy at.
  2. Max Profit: The best profit we could get if we sold today (Current Price - Min Price).
  • Initialize min_price = infinity, max_profit = 0.

  • For each price p:

  • Update min_price = min(min_price, p)

  • Update max_profit = max(max_profit, p - min_price)

Interactive Visualization
Step 1 / 1

Initializing...

1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.

Start Your Premium Prep