Skip to main content

121. Best Time to Buy and Sell Stock

easyAsked at Anduril

Find the maximum profit from a single buy-sell transaction in a price series. Anduril uses this as a single-pass greedy problem — the same linear scan logic applies to processing time-series sensor streams for anomaly detection in autonomous systems.

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

Source citations

Public interview reports confirming this problem appears in Anduril loops.

  • Glassdoor (2025-12)Listed in Anduril software engineer interview prep threads as a greedy warm-up.
  • Blind (2025-08)Anduril candidates report this style of single-pass optimization in phone-screen rounds.

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 decrease; no profitable transaction is possible.

Approaches

1. Brute Force

Try every pair (buy, sell) where buy < sell. Track the maximum difference.

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

Tradeoff: Correct but O(n^2). Always pivot to the single-pass approach; Anduril will ask why this isn't good enough.

2. Single-pass greedy

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

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

Tradeoff: O(n) time, O(1) space. At each price, we either update the running minimum buy price or try to beat the current best profit. The 'else if' isn't strictly necessary — you can use two separate ifs — but it's a readable optimization.

Anduril-specific tips

State the greedy invariant before coding: 'At each index, the maximum profit is prices[i] minus the minimum price seen before i.' Anduril engineers appreciate connecting this to real systems: the same scan-for-minimum logic appears in time-series baselines for sensor calibration. Be ready to extend to multiple transactions (LC 122) or a transaction fee (LC 714).

Common mistakes

  • Selling before buying — the sell day must be strictly after the buy day; make sure you update minPrice before computing profit.
  • Returning a negative number — the problem guarantees at least 0 profit if no valid transaction exists; initialize maxProfit to 0.
  • Initializing minPrice to prices[0] but then computing profit including day 0 as both buy and sell.
  • Using a two-pointer approach incorrectly — two pointers work but require careful handling when the right pointer finds a smaller price than the left.

Follow-up questions

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

  • LC 122: Best Time to Buy and Sell Stock II — unlimited transactions.
  • LC 309: with cooldown between transactions.
  • How would you adapt this for a continuous stream where prices arrive one at a 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 initialize minPrice to Infinity?

Any real price will be less than Infinity, so the first element will always set a valid minPrice on the first iteration.

Does the approach handle an all-decreasing array correctly?

Yes. minPrice continuously updates to lower values, but price - minPrice is always non-positive so maxProfit stays 0.

Can buy and sell on the same day?

The problem says 'a different day in the future', so no — profit would be 0, which is the floor anyway.

Practice these live with InterviewChamp.AI

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

Practice these live with InterviewChamp.AI →