16. Best Time to Buy and Sell Stock
easyAsked at ZoomFind the maximum profit from a single buy-and-sell of a stock.
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, find the maximum profit from one buy and one later sell. If you cannot profit, return 0.
Constraints
1 <= prices.length <= 10^50 <= prices[i] <= 10^4
Examples
Example 1
prices=[7,1,5,3,6,4]5Example 2
prices=[7,6,4,3,1]0Approaches
1. Brute force
Try every (buy, sell) pair.
- Time
- O(n^2)
- Space
- O(1)
let max=0; for(let i=0;i<n;i++) for(let j=i+1;j<n;j++) max=Math.max(max,prices[j]-prices[i]); return max;Tradeoff:
2. Running minimum
Track the minimum price seen and the best profit so far in one pass.
- Time
- O(n)
- Space
- O(1)
function maxProfit(prices) {
let lo = Infinity, best = 0;
for (const p of prices) {
if (p < lo) lo = p;
else if (p - lo > best) best = p - lo;
}
return best;
}Tradeoff:
Zoom-specific tips
Zoom likes running-minimum patterns because they parallel jitter-buffer min/max tracking — explain the streaming analog as a bonus.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Best Time to Buy and Sell Stock and other Zoom interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →