13. Best Time to Buy and Sell Stock
easyAsked at ActivisionFind the maximum profit from one buy/sell pair — Activision uses this to gauge single-pass thinking before pivoting to leaderboard rating-delta problems.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of daily prices, return the maximum profit you could achieve from buying on one day and selling on a later day. If no profit is possible, 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 pairs
Check every (buy, sell) pair.
- 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 tracking
Track running minimum price; max profit = best (price - min) seen so far in one sweep.
- Time
- O(n)
- Space
- O(1)
function maxProfit(prices) {
let min = Infinity, profit = 0;
for (const p of prices) {
if (p < min) min = p;
else if (p - min > profit) profit = p - min;
}
return profit;
}Tradeoff:
Activision-specific tips
Activision wants to see you collapse a two-pointer-looking problem into a single sweep — the same instinct maps to leaderboard rating-delta scans across a season window.
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 Activision interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →