Skip to main content

121. Best Time to Buy and Sell Stock

easyAsked at Hugging Face

Find the maximum profit from a single buy-sell transaction. Hugging Face uses this to assess greedy one-pass thinking — the same mindset needed to efficiently scan token log-probability arrays during beam search without re-processing elements.

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

Source citations

Public interview reports confirming this problem appears in Hugging Face loops.

  • Glassdoor (2025-12)Mentioned in Hugging Face SWE interview reports as a common greedy warm-up problem.
  • Blind (2025-08)Hugging Face coding threads cite this as a standard one-pass array scan question.

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: Prices only decrease, so no profitable transaction is possible.

Approaches

1. One-pass greedy

Track the minimum price seen so far and the maximum profit achievable at each step. Never look back.

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: O(n) time, O(1) space — optimal on both axes. The key insight is that you never need to reconsider a past price once you've found a lower minimum.

Hugging Face-specific tips

State the invariant out loud: 'At each index i, minPrice holds the cheapest buy opportunity seen in prices[0..i-1].' Hugging Face values engineers who can articulate loop invariants — this skill translates directly to reasoning about stateful inference loops in hosted model serving. Also mention that this is a special case of Kadane's algorithm on profit differences.

Common mistakes

  • Using a nested loop — O(n²) brute force is too slow for n=10^5.
  • Updating minPrice and profit in the wrong order — if you update minPrice before checking the profit for the current day, you might compute a zero-profit buy-and-sell on the same day.
  • Returning a negative number — clamp to 0 if no profitable trade exists.
  • Initializing minPrice to prices[0] without checking length — handle the single-element edge case.

Follow-up questions

An interviewer at Hugging Face may pivot to one of these next:

  • Best Time to Buy and Sell Stock II (LC 122) — unlimited transactions; greedy capture every upswing.
  • Best Time to Buy and Sell Stock with Cooldown (LC 309) — dynamic programming with a state machine.
  • How would you handle a stream of prices where you must decide to buy or sell in real time?

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 can't I buy and sell on the same day?

The problem requires selling strictly after buying. The one-pass algorithm naturally handles this because minPrice is updated to the current price only after computing the profit difference.

What if the array has only one price?

No transaction is possible — return 0. The loop runs once, minPrice = prices[0], profit stays 0.

How does this relate to Kadane's algorithm?

If you build a differences array (prices[i] - prices[i-1]), the maximum subarray sum equals the maximum profit — Kadane's is a direct analogue.

Practice these live with InterviewChamp.AI

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

Practice these live with InterviewChamp.AI →