Skip to main content

121. Best Time to Buy and Sell Stock

easyAsked at Canva

Find the maximum profit from a single buy-then-sell in a price array — Canva uses this single-pass sliding-minimum problem to confirm you can reason about 'running state' before handing you their real canvas-rendering performance metrics.

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 from one buy and one subsequent sell. 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 decrease; no profitable transaction is possible.

Approaches

1. Brute force (all pairs)

Try every buy-sell pair and track the maximum — O(n^2), fails on large inputs.

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. Optimal (single pass, running minimum)

Track the minimum price seen so far; at each step compute profit from buying at that minimum and selling today, updating the global maximum.

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:

Canva-specific tips

Canva interviewers expect you to state the invariant explicitly: 'At each index I maintain the lowest price seen so far to the left.' This pattern — running minimum / running maximum — recurs throughout their codebase when computing performance percentiles or layout bounds over a stream of measurements. Recognize and name the pattern before coding, and handle the edge case where all prices decrease (return 0, not a negative number) by initialising maxProfit to 0.

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 Canva interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →