Junior
Detailed answer
Arrays & Greedy
DSA & Coding Interviews
Explain Best Time to Buy and Sell Stock (one transaction).
Short answer: Track the minimum price so far while scanning left to right. At each day, compute profit = price − minSoFar and keep the maximum profit. One pass, O(1) extra space.
Problem statement
prices[i] is the stock price on day i. You may buy once and sell once later. Return the maximum profit (0 if no profit).
Interview approach
- Clarify: only one buy and one sell; sell after buy.
- Reject nested O(n²) “try every buy/sell pair” as too slow.
- Maintain minPrice and maxProfit while iterating.
- Update maxProfit when prices[i] − minPrice is better.
Sample solution
C#
int MaxProfit(int[] prices) {
int minPrice = int.MaxValue, best = 0;
foreach (int p in prices) {
if (p < minPrice) minPrice = p;
else best = Math.Max(best, p - minPrice);
}
return best;
}
Complexity
Time O(n), Space O(1).
Edge cases to mention
- Strictly decreasing prices → 0
- Single day → 0
- All equal prices → 0
Common follow-ups
- Unlimited transactions
- At most k transactions
- Cooldown / fees
Say “running minimum” out loud — it shows you understand the greedy invariant.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png