Skip to main content

9. Best Time to Buy and Sell Stock

easyAsked at Ramp

Maximize profit from a single buy and a single sell across a price series.

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

Problem

You are given an array prices where prices[i] is the price of a given stock on the ith day. Return the maximum profit you can achieve from one buy and one sell, in that order. 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

Nested loop over every (buy, sell) pair.

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:

2. Track running minimum

Keep the lowest price seen so far and the best profit if we sold today; single pass.

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

Tradeoff:

Ramp-specific tips

Ramp likes this problem because it mirrors how their FX rule engine picks the optimal settlement timing inside a billing window — single-pass with one running minimum signals you can do streaming optimization without a buffer.

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

Practice these live with InterviewChamp.AI →