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

  1. Clarify: only one buy and one sell; sell after buy.
  2. Reject nested O(n²) “try every buy/sell pair” as too slow.
  3. Maintain minPrice and maxProfit while iterating.
  4. 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.
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details