Skip to main content

10. Best Time to Buy and Sell Stock

easyAsked at Nubank

Find the max profit from a single buy/sell over a price series — a one-pass sliding minimum that Nubank uses as an analog for FX/credit risk windowing.

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

Problem

You are given an array prices where prices[i] is the price of an asset on day i. Return the maximum profit achievable from one buy and one later sell. If no profit is possible, 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

Example 2

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

Approaches

1. Brute force all pairs

Try every (buy, sell) pair.

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

Tradeoff:

2. Single-pass min-tracker

Track the running minimum buy price; at each day compute profit-if-sold-today against the min so far.

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

Tradeoff:

Nubank-specific tips

At Nubank, frame the sliding-min as risk-window state in a credit-card ledger — they want to see you can map a textbook DP into a money-domain stream.

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

Practice these live with InterviewChamp.AI →