Skip to main content

121. Best Time to Buy and Sell Stock

easyAsked at Elastic

Find the maximum profit from a single buy-low-sell-high transaction. Elastic uses this pattern to test sliding-window and running-minimum thinking — the same mental model used when computing rolling aggregations over time-series log data in Elasticsearch.

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

Source citations

Public interview reports confirming this problem appears in Elastic loops.

  • Glassdoor (2025-12)Elastic SWE onsite reports list stock profit and sliding-window problems as recurring warm-up exercises.
  • Blind (2025-10)Elastic interview threads note time-series and running-min/max patterns appear frequently, tying to Elasticsearch's aggregation capabilities.

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: Prices only decline. No profitable transaction is possible, so return 0.

Approaches

1. One-pass running minimum

Track the minimum price seen so far and the maximum profit achievable. For each day, update the running minimum and check if selling today beats the current best profit.

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; // found a cheaper buy day
    } else if (price - minPrice > maxProfit) {
      maxProfit = price - minPrice; // found a better profit
    }
  }
  return maxProfit;
}

Tradeoff: Optimal — single pass, constant space. The running-minimum pattern is exactly how Elasticsearch computes rolling min aggregations over a time-series index.

Elastic-specific tips

Elastic interviewers appreciate when you frame this as a time-series problem: 'At each point in time, what is the best buy price I have seen so far, and does selling now beat my current best profit?' This maps naturally to how Kibana's time-range queries compute running statistics over log streams. Be prepared for the follow-up: multiple transactions allowed (LC 122) or at most k transactions (LC 188).

Common mistakes

  • Allowing selling before buying — ensure sell index > buy index by updating minPrice before checking profit.
  • Returning a negative profit — always clamp to 0 when no profitable transaction exists.
  • Using a nested loop O(n²) approach — unacceptable for the 10^5 constraint.
  • Confusing this with the multi-transaction variant — LC 121 is exactly one transaction.

Follow-up questions

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

  • Best Time to Buy and Sell Stock II (LC 122) — unlimited transactions; greedy sum of positive differences.
  • Best Time to Buy and Sell Stock with Cooldown (LC 309) — adds a rest-day constraint after selling.
  • How would you compute rolling maximum profit over a sliding 30-day window across millions of log entries?

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 update minPrice before checking profit?

Updating first ensures you never compute profit by buying and selling on the same day (price - price = 0, which is harmless) and never sell before buying.

Why initialize minPrice to Infinity?

Any real price will be less than Infinity on the first iteration, so the running minimum is set correctly regardless of the first price.

Practice these live with InterviewChamp.AI

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

Practice these live with InterviewChamp.AI →