Skip to main content

4. Best Time to Buy and Sell Stock

easyAsked at Square

Find the max profit from one buy and one sell over a price array. Square uses this to test whether you spot the single-pass running-minimum pattern — the same trick they apply to compute peak-vs-trough deltas on Cash App balance histories.

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

Source citations

Public interview reports confirming this problem appears in Square loops.

  • Glassdoor (2026-Q1)Cash App phone screen, asked alongside Two Sum.
  • LeetCode Discuss (2025)Square Capital lending team.

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 = 5.

Example 2

Input
prices = [7,6,4,3,1]
Output
0

Explanation: No transactions can be made; return 0.

Approaches

1. Brute force every pair

Try every (buy, sell) pair where buy < sell and track the max difference.

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

Tradeoff: TLEs at the 10^5 ceiling — Square interviewers will check that you immediately see why.

2. Running minimum, single pass

Track the minimum price seen so far. At each index compute price - min and update best.

Time
O(n)
Space
O(1)
function maxProfit(prices) {
  let minSoFar = Infinity;
  let best = 0;
  for (const p of prices) {
    if (p < minSoFar) minSoFar = p;
    else if (p - minSoFar > best) best = p - minSoFar;
  }
  return best;
}

Tradeoff: Single pass, O(1) space. The insight: at index i, the best sell is constrained only by the lowest buy point you've seen so far.

Square-specific tips

Square interviewers want you to state the invariant ('minSoFar is the cheapest day in [0..i]') before coding. Mention that this generalizes — every 'max gap with order constraint' problem follows the same template — and you'll get bonus signal in Cash App interviews where balance-delta queries reuse this pattern.

Common mistakes

  • Updating min AND computing profit in the same branch — when today is the new min, you can't sell today.
  • Initializing best to -Infinity — return 0 if no profitable trade exists.
  • Trying DP with a 2D table — overengineered for this single-transaction variant.

Follow-up questions

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

  • Multiple transactions allowed (LC 122).
  • At most k transactions (LC 188) — true DP.
  • Add a cooldown day after each sale (LC 309).

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 use 'else if' instead of always checking the profit?

Style only — both work. Skipping the profit calc when we just set a new min is a minor optimization.

Can the answer be negative?

No — the spec says return 0 if no profit. You're not forced to transact.

Practice these live with InterviewChamp.AI

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

Practice these live with InterviewChamp.AI →