16. Best Time to Buy and Sell Stock
easyAsked at OlaMaximize profit from a single buy/sell of a daily price array.
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 ith day. You want to maximize your profit by choosing a single day to buy and a different later day to sell. Return the maximum profit; 0 if not 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 day with every later sell day.
- Time
- O(n^2)
- Space
- O(1)
let max = 0;
for (let i=0;i<prices.length;i++)
for (let j=i+1;j<prices.length;j++)
max = Math.max(max, prices[j]-prices[i]);
return max;Tradeoff:
2. Single pass minimum
Track the lowest price so far and update the best profit each step.
- Time
- O(n)
- Space
- O(1)
function maxProfit(prices) {
let min = Infinity, best = 0;
for (const p of prices) {
min = Math.min(min, p);
best = Math.max(best, p - min);
}
return best;
}Tradeoff:
Ola-specific tips
Ola sees this as the entry to streaming-aggregate questions; relate it to capturing the best surge-pricing window seen so far in a live fare feed.
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 Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →