6. Best Time to Buy and Sell Stock
easyAsked at SwiggyFind the max profit from one buy-sell of a stock given daily prices.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given prices[i] = price of a stock on day i, return the maximum profit you can make by buying once 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
Try every (buy, sell) pair.
- Time
- O(n^2)
- Space
- O(1)
let best=0;
for (let i=0;i<n;i++)
for (let j=i+1;j<n;j++)
best=Math.max(best, prices[j]-prices[i]);
return best;Tradeoff:
2. Single pass min tracking
Track running minimum and best profit-if-sold-today as you scan once. Profit = current price minus best buy seen so far.
- Time
- O(n)
- Space
- O(1)
function maxProfit(prices) {
let minPrice = Infinity;
let best = 0;
for (const p of prices) {
if (p < minPrice) minPrice = p;
else if (p - minPrice > best) best = p - minPrice;
}
return best;
}Tradeoff:
Swiggy-specific tips
Swiggy maps this onto surge-pricing decisions; the bonus signal is verbalizing why local minima beat tracking pair-wise diffs.
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 Swiggy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →