Skip to main content

12. Best Time to Buy and Sell Stock

easyAsked at GitLab

Find the maximum profit from a single buy/sell of one stock, given a daily price array.

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

Problem

You are given an array prices where prices[i] is the stock price on day i. Choose a single day to buy and a later day to sell to maximize profit. 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 nested

Try every (buy, sell) pair and track max diff.

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

Tradeoff:

2. Single-pass min tracker

Walk left-to-right keeping the running min price; profit at i is price[i] - minSoFar.

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

Tradeoff:

GitLab-specific tips

GitLab frames this as a streaming-metric problem — they will ask how you would adapt the single-pass solution to a continuous pipeline-duration feed coming off a runner pool.

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

Practice these live with InterviewChamp.AI →