Skip to main content

16. Best Time to Buy and Sell Stock

easyAsked at Lyft

Find the maximum single-buy single-sell profit from a price array.

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

Problem

You are given an array prices where prices[i] is the price of a stock on day i. You want to maximize profit by choosing one day to buy and a later day to sell — return the max profit, or 0 if no profit 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. Try all buy days

For each buy day, scan future days for max profit.

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 min-tracker

Track running minimum price and compute max-of-difference in one pass.

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

Tradeoff:

Lyft-specific tips

Lyft connects this pattern to surge pricing — they want you to articulate the running-minimum trick because dispatchers use the same idea to track lowest fare windows.

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

Practice these live with InterviewChamp.AI →