Skip to main content

24. Best Time to Buy and Sell Stock

easyAsked at Glassdoor

Glassdoor coaches job-seekers on offer timing — and this single-pass min-tracking problem is their go-to warmup that doubles as a filter for candidates who conflate 'track the minimum seen' with 'compare all pairs'.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an array prices where prices[i] is the price of a stock on day i, return the maximum profit you can achieve by buying on one day and selling on a later day. 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 on day 2 (price=1), sell on day 5 (price=6). Profit = 6-1 = 5.

Example 2

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

Explanation: Prices only fall; no transaction yields a profit.

Approaches

1. Brute force — all pairs

Check every buy-sell pair. O(n^2) — fails at 10^5 prices.

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

Tradeoff:

2. Single pass — track running minimum

Track the lowest price seen so far. At each day compute profit if sold today; update the maximum. One pass, O(n).

Time
O(n)
Space
O(1)
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;
}

Tradeoff:

Glassdoor-specific tips

Glassdoor interviewers use this as a quick filter — if you immediately say 'I'll try all pairs,' they'll note it and move on. The expected answer is O(n) with the running-minimum observation. Verbalize the invariant: 'at every price I know the cheapest I could have bought before this day, so I compute today's profit in O(1).' Also handle the no-profit case cleanly by initializing maxProfit to 0 rather than negative infinity.

Solve it now

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

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Best Time to Buy and Sell Stock and other Glassdoor interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →