easy

Best Time to Buy and Sell Stock

Find the maximum profit from buying on one day and selling on a later day.

1. Define the problem

Best Time to Buy and Sell Stock

You are given an array prices where pricesi is the price of a given stock on the ith 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 you can achieve from this transaction. If you cannot achieve any profit, return 0. Track the minimum price seen so far in one pass, and compare each day against that running minimum to find the best profit.

Constraints

  • 1 ≤ prices.length ≤ 105
  • 0 ≤ pricesi ≤ 104

Example

Inputprices = [7, 1, 5, 3, 6, 4]
Output5

Explanation Buy on day 1 (price = 1) and sell on day 4 (price = 6), profit = 6 - 1 = 5.

2. Visualize the solution

Track the running minimum price

Track the running minimum price
Statusinit

Day 0: price 7 — set as running minimum. Best profit = 0.

What happens in this step

minPrice = prices[0] = 7
bestProfit = 0

No later day has been compared yet, so profit starts at 0.
Step 1 of 6

Steps to visualize

  1. Start with the running minimum at the first day's price and best profit at 0.
  2. Move right one day at a time.
  3. If today's price is lower than the running minimum, update the minimum.
  4. Otherwise compute profit as price minus the running minimum and update best if it improves.
  5. Stop after scanning the last day.
3. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Track the running minimum price
Statusinit

Day 0: price 7 — set as running minimum. Best profit = 0.

What happens in this step

minPrice = prices[0] = 7
bestProfit = 0

No later day has been compared yet, so profit starts at 0.
Step 1 of 6
4. Solution

Solution

solution.tsTypeScript
function maxProfit(prices) {
  if (prices.length === 0) {
    throw new Error("prices must contain at least one price");
  }

  let minPrice = prices[0];
  let bestProfit = 0;

  for (let i = 1; i < prices.length; i++) {
    if (prices[i] < minPrice) {
      minPrice = prices[i];
    } else {
      bestProfit = Math.max(bestProfit, prices[i] - minPrice);
    }
  }

  return bestProfit;
}
Time
O(n)
Space
O(1)
5. Test cases

Test cases

InputExpectedCovers
prices = [7, 1, 5, 3, 6, 4]5example from the docstring
prices = [5]0smallest valid input: single day, no transaction possible
prices = [3, 3, 3, 3]0all identical prices
prices = [9, 7, 5, 3, 1]0prices only decrease, so no profit is possible
prices = [1, 2, 3, 4, 5]4prices only increase: best is buy first, sell last
prices = [0, 0, 0, 0]0boundary value: prices can be 0
prices = [3, 2, 6, 5, 0, 3, 9, 4]9larger, hand-verified case