Skip to main content

121. Best Time to Buy and Sell Stock

easyAsked at HP

HP's financial and enterprise analytics teams process time-series data from equipment telemetry and cost-optimization pipelines. This problem tests single-pass reasoning over sequential data — the same pattern used when scanning sensor readings for peak-to-trough performance differences.

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

Source citations

Public interview reports confirming this problem appears in HP loops.

  • Glassdoor (2026-Q1)Reported in HP data-engineering and backend SWE interview round summaries as a classic greedy screening question.
  • Blind (2025-09)HP SWE interview prep discussions list this as a standard easy question in phone-screen and first technical rounds.

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; no profitable transaction is possible, return 0.

Approaches

1. Brute force

Try every (buy, sell) pair and track the maximum profit.

Time
O(n²)
Space
O(1)
function maxProfit(prices) {
  let max = 0;
  for (let i = 0; i < prices.length; i++) {
    for (let j = i + 1; j < prices.length; j++) {
      max = Math.max(max, prices[j] - prices[i]);
    }
  }
  return max;
}

Tradeoff: Too slow for large inputs. Acceptable as a starting point to articulate, but always follow with the linear approach.

2. Single pass (greedy min-tracking)

Track the minimum price seen so far. At each day, compute profit if selling today and update the running maximum.

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. The optimal solution. By maintaining the running minimum and updating profit at each step, we capture the best buy-low-sell-high window without nested loops.

HP-specific tips

HP enterprise interviews appreciate explicit reasoning about why you initialize minPrice to Infinity rather than prices[0] — it makes the edge case of a single-element array clean. Draw a quick timeline diagram to make the 'min-so-far' invariant clear. Expect a follow-up about multiple transactions (LC 122) or a cooldown period.

Common mistakes

  • Allowing sell before buy — always compute profit as prices[j] - prices[i] where j > i, which the single-pass approach enforces naturally.
  • Initializing maxProfit to a negative number — the problem says return 0 if no profit is possible.
  • Updating minPrice and checking profit in the wrong order in the same iteration — you must update minPrice first.
  • Not handling the single-element array — no transaction is possible; return 0.

Follow-up questions

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

  • What if you could make at most two transactions (LC 123)?
  • What if you could make unlimited transactions but needed a cooldown day after each sale (LC 309)?
  • How would you find the actual buy and sell day indices, not just the profit value?

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 not track both min and max simultaneously?

The max price must come after the min price in time. Tracking a global max independently doesn't enforce the ordering constraint — use the min-so-far pattern instead.

What if all prices are the same?

Every day's profit calculation yields 0, so maxProfit remains 0 — the correct answer.

Can you solve this with Kadane's algorithm?

Yes — compute the daily price differences and apply Kadane's maximum-subarray algorithm. Both approaches are O(n); the min-tracking version is more direct to explain.

Practice these live with InterviewChamp.AI

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

Practice these live with InterviewChamp.AI →