8. Best Time to Buy and Sell Stock
easyAsked at FlipkartFind the max single-transaction profit from a price stream — Flipkart maps this to spotting the best discount window during a Big Billion Days sale event.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
You are given an array prices where prices[i] is the price on the ith day. Choose one day to buy and a later day to sell to maximize profit. Return the maximum profit; 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
Check every (buy, sell) pair.
- Time
- O(n^2)
- Space
- O(1)
for (let i=0;i<n;i++)
for (let j=i+1;j<n;j++)
best = Math.max(best, prices[j] - prices[i]);Tradeoff:
2. Single pass min tracking
Track the minimum seen so far; for each day compute profit against that minimum and keep the best. One scan, O(1) memory.
- 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:
Flipkart-specific tips
Flipkart loves when you connect this to their sale-event price-tracking dashboards and discuss handling missing or out-of-order timestamps.
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 Flipkart interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →