Skip to main content

4. Best Time to Buy and Sell Stock

easyAsked at ByteDance

Find the maximum profit from a single buy-sell pair — ByteDance uses it to test running-minimum bookkeeping before scaling to streaming ranking signals.

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

Problem

Given an array prices where prices[i] is the price of a stock on day i, return the maximum profit you can achieve from buying on one day and selling on a later day. Return 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

Check every pair (i, j) with j > i.

Time
O(n^2)
Space
O(1)
let best = 0;
for (let i=0;i<p.length;i++)
  for (let j=i+1;j<p.length;j++)
    best = Math.max(best, p[j]-p[i]);

Tradeoff:

2. Running minimum

Track the lowest price seen so far; the best profit is the max gap from that minimum to today's price.

Time
O(n)
Space
O(1)
function maxProfit(prices) {
  let lo = Infinity, best = 0;
  for (const p of prices) {
    lo = Math.min(lo, p);
    best = Math.max(best, p - lo);
  }
  return best;
}

Tradeoff:

ByteDance-specific tips

ByteDance values the framing that this is a streaming-min problem, which mirrors how their recommendation system tracks running engagement minima across watch sessions.

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

Practice these live with InterviewChamp.AI →