Skip to main content

121. Best Time to Buy and Sell Stock

easyAsked at IBM

Best Time to Buy and Sell Stock is IBM's array-traversal screener for SWE phone screens and the Watson/Research data-engineering track. The interviewer is grading whether you can derive the running-minimum invariant on a single pass instead of falling into the brute-force double loop.

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

Source citations

Public interview reports confirming this problem appears in IBM loops.

  • Glassdoor (2026-Q1)Repeated mention in IBM SWE and cloud-engineering phone screens.
  • LeetCode (2026-Q1)Top-30 IBM-tagged problem on the company-frequency list.
  • GeeksforGeeks (2025-10)Cited in IBM interview-experience archive (multiple campus recruits).

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), sell on day 5 (price = 6). Profit = 6 - 1 = 5.

Example 2

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

Explanation: No transaction is profitable; return 0.

Approaches

1. Brute force — every (buy, sell) pair

For each day i, try every later day j and track the maximum (prices[j] - prices[i]).

Time
O(n^2)
Space
O(1)
function maxProfitBrute(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: Simplest to derive. At 10^5 prices, n^2 is 10^10 operations — times out. Useful only as a starting point you immediately optimize away.

2. Single pass with running minimum (optimal)

Track the lowest price seen so far. At each step, compute (current price - running min) as the profit if you sold today.

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

Tradeoff: O(n) single pass with O(1) memory. The invariant — 'minSoFar is the cheapest buy across all days up to today' — is the whole problem; once you state it, the code writes itself.

IBM-specific tips

IBM interviewers reward candidates who narrate the invariant before coding. Say: 'At each day, the best sell price is today's price minus the cheapest price I've seen so far. So I only need to track one number, the running minimum.' Coding before stating the invariant signals you got lucky; stating it first signals you derived the answer.

Common mistakes

  • Tracking the global minimum AND maximum separately — broken because the max must come AFTER the min in time.
  • Initializing bestProfit to a large positive number instead of 0 (no transaction = 0 profit).
  • Off-by-one: comparing prices[j] - prices[i] when i could equal j (must be different days).
  • Returning a negative profit instead of 0 when prices is monotonically decreasing.

Follow-up questions

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

  • Best Time to Buy and Sell Stock II — unlimited transactions allowed (LeetCode 122).
  • Best Time to Buy and Sell Stock III — at most two transactions (LeetCode 123).
  • Best Time to Buy and Sell Stock with Cooldown (LeetCode 309).
  • What if you can hold at most one share but include a transaction fee?

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 doesn't tracking max - min globally work?

Because the max must come AFTER the min chronologically. If prices = [7, 1, 5, 3, 6, 4], the global min is 1 (day 2) and global max is 7 (day 1) — but day 1 is before day 2, so you can't buy after you sell. The running-minimum approach enforces the time order.

Why is this problem listed as IBM-favorite?

It's a perfect 5-minute warm-up that filters candidates who can derive an invariant from those who can't. IBM phone-screen reports consistently list it as the opener before harder array/DP problems.

Free learning resources

Curated free links for this problem.

Practice these live with InterviewChamp.AI

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

Practice these live with InterviewChamp.AI →