03. Best Time to Buy and Sell Stock

Difficulty:EasyPattern:Greedy / Single PassTime:O(n)Space:O(1)

Given an array prices where prices[i] is the stock price on day i, return the maximum profit you can achieve from a single transaction.

How It Works & Algorithmic Design

This uses a Single-Pass Greedy Running Minimum strategy:

  1. Variables: Track minPrice = Infinity and maxProfit = 0.
  2. Iteration: Loop through each stock price in prices:
    • If the current price is lower than minPrice, update minPrice = price.
    • Otherwise, calculate potential profit: price - minPrice. If this profit exceeds maxProfit, update maxProfit.
  3. Return: Return maxProfit after scanning all prices.

Why This Approach Works Best

Checking every pair of buying/selling days with nested loops takes $O(n^2)$ time. Tracking the lowest price seen so far allows maximum profit calculation in $O(n)$ time and $O(1)$ space.

Example Walkthrough

Input

prices = [7, 1, 5, 3, 6, 4]

Daily stock prices.

Trace

7 (min=7) -> 1 (min=1) -> 5 (profit=4) -> 3 -> 6 (profit=5, max=5) -> 4

Tracks minPrice and maxProfit concurrently.

Output

5

Buy on day 2 (price=1), sell on day 5 (price=6).

Answer: Maximum stock profit calculation

function maxProfit(prices) {
  let minPrice = Infinity;
  let maxProfit = 0;
  for (const price of prices) {
    if (price < minPrice) {
      minPrice = price;
    } else if (price - minPrice > maxProfit) {
      maxProfit = price - minPrice;
    }
  }
  return maxProfit;
}

Track the minimum price seen so far and update profit whenever a higher selling price occurs.

Key Takeaways
  • Stock must be bought before it can be sold (left-to-right order dependency).

  • Maintain running minimum price to evaluate maximum potential gain.

  • Single pass achieves $O(n)$ time and $O(1)$ space.