Skip to main content

121. Best Time to Buy and Sell Stock

easyAsked at JPMorgan

Given a day-indexed price array, find the maximum profit from one buy and one later sell. JPMorgan asks this on nearly every market-data and equities-tech SDE loop because the optimal single-pass min-tracking solution generalises directly to streaming P&L computation.

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

Source citations

Public interview reports confirming this problem appears in JPMorgan loops.

  • Glassdoor (2026-Q1)Repeated in JPMorgan equities/markets-tech SDE phone-screen and onsite reports through Q1 2026.
  • LeetCode (2026-Q1)One of the most-tagged JPMorgan problems on the LeetCode company tag page.
  • Blind (2025-12)Recurring JPMC SWE-II 'classic warm-up' across multiple onsite write-ups.

Problem

You are given an array prices where prices[i] is the price of a given stock on the i-th 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 transaction is done; max profit = 0.

Approaches

1. Brute-force every pair

Check every (buy_day, sell_day) pair with sell > buy and track the max profit.

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: Conceptually simplest but TLEs at the 10^5 constraint. Useful only as a warm-up to motivate the single-pass minimum-tracking version.

2. Single pass tracking running minimum (optimal)

Maintain the minimum price seen so far. For each day, candidate profit = today - minSoFar. Take the max.

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: O(n) time, O(1) space, single forward pass — the production-grade answer for any streaming-price feed. JPMorgan interviewers explicitly note this generalises to running-P&L on tick data.

JPMorgan-specific tips

On markets-tech and equities-tech loops, JPMorgan interviewers ask this and then immediately follow up with 'now imagine prices arrives as a stream — what changes?' The expected answer is 'nothing, the algorithm is already online and O(1) state per tick'. Articulating that connection on the first answer (without waiting for the follow-up) is what separates a strong-hire from a hire on the rubric.

Common mistakes

  • Initialising the running minimum to prices[0] then iterating from index 0 again (double-counts day 0).
  • Updating profit before checking the new minimum, missing the case where today is the new low.
  • Forgetting that the sell must come strictly after the buy (returning a positive value when prices is monotonically decreasing).
  • Returning a negative number instead of 0 when no profit is possible.

Follow-up questions

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

  • What if you can buy and sell multiple times? (LC 122 — sum every positive delta.)
  • What if you can do at most 2 transactions? (LC 123 — two-state DP.)
  • What if you can do at most k transactions? (LC 188 — k-state DP.)
  • What if there is a cooldown day after each sell? (LC 309 — state machine.)
  • What if the prices array arrives as a stream and you must answer max profit so far after every tick?

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 does the running-minimum approach work in one pass?

The optimal sell day j has profit prices[j] - min(prices[0..j-1]). If you maintain the running min while scanning left-to-right, every j sees the correct min for its prefix, so taking the max over all j gives the global optimum.

Does JPMorgan accept the DP framing (Kadane-style) for this problem?

Yes. Many candidates treat it as 'max subarray of price deltas' which is equivalent. Either framing is accepted, but the running-min explanation tends to land better with markets-tech interviewers because it maps directly to how a trading book actually tracks realised gain.

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

Practice these live with InterviewChamp.AI →