Skip to main content

10. Best Time to Buy and Sell Stock

easyAsked at Wise

Find the maximum profit from one buy/sell in an FX-style price series — a thinly disguised cross-border arbitrage matching question.

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

Problem

Given an array of prices where prices[i] is the price of an asset on day i, return the maximum profit from buying on one day and selling on a later day. If no profit is possible, return 0.

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4
  • Sell day must be after buy day

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. All pairs

Try every (buy, sell) pair with i<j and track the largest difference.

Time
O(n^2)
Space
O(1)
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:

2. Single pass running min

Walk left-to-right keeping the cheapest price seen so far; profit at day i is price[i] minus that running min. Take the max.

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:

Wise-specific tips

Wise frames this internally as the cross-border FX matching problem — they expect you to spot the running-min trick fast because their batch matcher uses the same one-pass shape.

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 Wise interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →