Skip to main content

10. Best Time to Buy and Sell Stock

easyAsked at Revolut

Find the max profit from a single buy-then-sell over a price series, a Revolut warm-up that mirrors picking the single best entry/exit on an intraday FX feed.

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

Problem

Given an array prices where prices[i] is the price on day i, return the maximum profit you can achieve from one buy followed by one later sell. Return 0 if no profit is possible.

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4

Examples

Example 1

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

Example 2

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

Approaches

1. Brute force pairs

Try every (buy, sell) pair.

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

Tradeoff:

2. Track rolling minimum

Walk once tracking the lowest seen price and best profit relative to it. Linear time, constant space.

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

Tradeoff:

Revolut-specific tips

Revolut likes you to mention that intraday FX uses integer minor units, not floats — so the running-minimum comparison should always be on integers to avoid rounding the spread.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

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

Practice these live with InterviewChamp.AI →