Skip to main content

5. Best Time to Buy and Sell Stock

easyAsked at Snap

Find the maximum profit from a single buy/sell on a price-per-day array. Snap uses this to verify you can convert a naive nested loop into a single-pass min-tracking sweep.

By Sam K., Founder, InterviewChamp.AI · Last verified

Source citations

Public interview reports confirming this problem appears in Snap loops.

  • Glassdoor (2026-Q1)Common Snap new-grad warm-up.
  • Blind (2025-09)Frequently paired with Two Sum to test pattern-recognition speed.

Problem

You are given an array prices where prices[i] 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. If no profit is possible, return 0.

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4

Examples

Example 1

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

Explanation: Buy at 1, sell at 6.

Example 2

Input
prices = [7,6,4,3,1]
Output
0

Explanation: Prices only decrease; no profit.

Approaches

1. Brute-force every pair

For every i, scan j > i and track max(prices[j] - prices[i]).

Time
O(n^2)
Space
O(1)
function maxProfit(prices) {
  let best = 0;
  for (let i = 0; i < prices.length; i++) {
    for (let j = i + 1; j < prices.length; j++) {
      best = Math.max(best, prices[j] - prices[i]);
    }
  }
  return best;
}

Tradeoff: Quadratic — too slow for 10^5 inputs. Show this only as the motivating baseline.

2. Single-pass min-tracking (optimal)

Walk left to right keeping the lowest price seen so far. At each step, candidate profit is current - min. Update both as you go.

Time
O(n)
Space
O(1)
function maxProfit(prices) {
  let minSoFar = Infinity;
  let best = 0;
  for (const p of prices) {
    if (p < minSoFar) minSoFar = p;
    else if (p - minSoFar > best) best = p - minSoFar;
  }
  return best;
}

Tradeoff: Linear time, constant space. The 'min so far' is the recurring DP-on-prefix pattern that recurs across many Snap problems.

Snap-specific tips

Snap rewards candidates who articulate the prefix-min pattern out loud. Bonus signal: connect it to streaming analytics — Snap engineers think of this kind of single-pass scan as the same shape they use to compute running statistics on Stories view-counts.

Common mistakes

  • Initializing best to -Infinity instead of 0 — the problem guarantees non-negative profit, return 0 when no trade is profitable.
  • Updating minSoFar AFTER computing the candidate profit — that allows selling and buying on the same day.
  • Trying to track maxSoFar instead of minSoFar — works but conceptually awkward.

Follow-up questions

An interviewer at Snap may pivot to one of these next:

  • Allow unlimited transactions (LC 122).
  • Allow at most two transactions (LC 123).
  • Allow k transactions (LC 188) — DP table required.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

FAQ

Why use else if instead of two separate checks?

If we just updated minSoFar to today's price, then today - minSoFar == 0, which can't beat the running best. The else-if simply skips a redundant comparison. Both versions are correct.

Does the array need to be modified?

No — we only read prices. The algorithm is read-only with O(1) extra space, which is part of what makes it the textbook optimal.

Companies that also ask Best Time to Buy and Sell Stock