Skip to main content

121. Best Time to Buy and Sell Stock

easyAsked at Linear

Find the maximum profit from a single buy-then-sell transaction. Linear uses this to see if you recognize the 'running minimum' pattern — iterating once while tracking the cheapest buy price seen so far.

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

Source citations

Public interview reports confirming this problem appears in Linear loops.

  • Glassdoor (2026-Q1)Reported as a warm-up problem in Linear SWE phone screen threads.
  • r/cscareerquestions (2025-09)Frequently cited in Linear early-round interview discussions.

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 from this transaction. If you cannot achieve any profit, 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) and sell on day 5 (price=6). Profit = 6-1 = 5.

Example 2

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

Explanation: No profitable transaction is possible; return 0.

Approaches

1. Brute force all pairs

Try every buy/sell pair and track the maximum profit.

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: Correct but O(n^2). Only acceptable as a stepping stone before the one-pass solution.

2. One pass with running minimum (optimal)

Track the minimum price seen so far; at each step compute potential profit and update the global max.

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 {
      maxProfit = Math.max(maxProfit, price - minPrice);
    }
  }
  return maxProfit;
}

Tradeoff: O(n) time, O(1) space. The key insight: for any sell day, the optimal buy day is the minimum of all previous days — so track that minimum as you go.

Linear-specific tips

Linear interviewers like candidates who can name the pattern. When you arrive at the one-pass solution, say something like: 'This is the running-minimum pattern — whenever I need to maximize profit against a historical cheapest value, I update the min on the fly.' Naming patterns signals experience with real codebases.

Common mistakes

  • Allowing selling before buying — the sell index must be strictly after the buy index, which the one-pass approach enforces naturally.
  • Returning negative profit — initialize maxProfit to 0, not -Infinity, because no trade = 0 profit.
  • Updating minPrice and maxProfit in the wrong order — compute profit before updating the minimum.

Follow-up questions

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

  • Best Time to Buy and Sell Stock II (LC 122) — unlimited transactions (greedy sum of positive deltas).
  • Best Time to Buy and Sell Stock with Cooldown (LC 309) — adds a rest day constraint (DP).
  • What if you want to return the buy and sell day indices, not just the profit?

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 initialize minPrice to Infinity?

The first price is guaranteed to be less than Infinity, so it becomes the initial minimum without special-casing day 0.

Why can't I just use Math.min and Math.max on the full array?

The minimum must come before the maximum in the array. The global min and global max might be in the wrong order, so you need to enforce the left-to-right constraint by scanning once.

What if all prices are the same?

Every day equals minPrice; the else branch computes profit = 0 every time; maxProfit stays 0. Correct.

Practice these live with InterviewChamp.AI

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

Practice these live with InterviewChamp.AI →