Skip to main content

121. Best Time to Buy and Sell Stock

easyAsked at HubSpot

HubSpot includes this classic sliding-window / greedy problem to test whether you can track a running minimum while computing a maximum difference — a pattern that recurs in revenue-trend analysis across their sales CRM data pipelines.

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

Source citations

Public interview reports confirming this problem appears in HubSpot loops.

  • Glassdoor (2026-Q1)Cited in HubSpot SWE interview reports as a common warm-up problem in phone screens.
  • Blind (2025-10)HubSpot engineering candidates list Buy and Sell Stock as a recurring screen question.

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

Approaches

1. One-pass greedy (track min price)

Iterate through prices tracking the minimum price seen so far. At each day, compute profit if you sold today (price - minSoFar) and update the global max 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;
    } else if (price - minPrice > maxProfit) {
      maxProfit = price - minPrice;
    }
  }
  return maxProfit;
}

Tradeoff: Single pass, O(1) space. This is the optimal and expected answer. The key insight is that the buy day must come before the sell day, so tracking minPrice as you iterate left-to-right naturally enforces the ordering constraint.

HubSpot-specific tips

Frame the intuition before coding: 'I need the lowest buy price seen so far and the highest profit achievable from any future day.' HubSpot interviewers appreciate when you draw the connection to real-world data patterns — like tracking the minimum deal-open value in a revenue funnel to find the best close window. Always check the decreasing-prices edge case (return 0) before declaring your solution complete.

Common mistakes

  • Initializing minPrice to prices[0] without considering that a later lower price might be missed — initializing to Infinity is safer.
  • Allowing buy and sell on the same day — the sell must happen strictly after the buy.
  • Returning a negative profit — the minimum return is 0 (no transaction is better than a loss).
  • Trying a two-pointer approach from both ends — this doesn't work because buy must precede sell in time.

Follow-up questions

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

  • Best Time to Buy and Sell Stock II (LC 122) — unlimited transactions allowed.
  • Best Time to Buy and Sell Stock with Cooldown (LC 309) — one-day cooldown between sell and next buy.
  • How would you solve this if you could complete at most k transactions (LC 188)?

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 and not prices[0]?

Both work, but Infinity avoids off-by-one issues if the array is empty (though constraints say length >= 1). It also makes the algorithm's invariant clearer: minPrice is always the smallest price seen so far.

Does this handle an all-decreasing array?

Yes — every price - minPrice will be <= 0, so maxProfit never updates from its initial value of 0.

What's the difference between this and the two-pointer approach?

Two pointers work for finding pairs in sorted arrays; here order matters (buy before sell), so tracking a running minimum is the correct pattern.

Practice these live with InterviewChamp.AI

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

Practice these live with InterviewChamp.AI →