Skip to main content

17. Best Time to Buy and Sell Stock

easyAsked at Expedia

Maximize profit from one buy and one sell of a stock given daily prices.

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. 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. Return the maximum profit, or 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

Check every (buy, sell) pair.

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]);

Tradeoff:

2. Single pass min tracking

Track running minimum, update best diff. Expedia uses this exact pattern for lowest-fare-so-far during price-watch.

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

Tradeoff:

Expedia-specific tips

Expedia interviewers love this problem because it directly mirrors price-watch alerts — make sure you tie your solution to that real-world flight-fare scenario.

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

Practice these live with InterviewChamp.AI →