16. Best Time to Buy and Sell Stock
easyAsked at TripAdvisorFind the maximum profit from buying and selling a stock once.
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 i-th day. Find the maximum profit you can achieve by choosing a single day to buy one stock and choosing a different day in the future to sell it. Return 0 if no profit is possible.
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 pairs
Try every (buy, sell) pair with i < j.
- 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. Track running minimum
Single pass: maintain min-so-far, candidate profit = price - min. Take max.
- Time
- O(n)
- Space
- O(1)
function maxProfit(prices) {
let minP = Infinity, best = 0;
for (const p of prices) {
if (p < minP) minP = p;
else if (p - minP > best) best = p - minP;
}
return best;
}Tradeoff:
TripAdvisor-specific tips
TripAdvisor uses single-pass max-window problems to gauge if you can analyze price-history streams for hotel rate trends without nested loops.
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 TripAdvisor interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →