How to Explain Best Time to Buy and Sell Stock in a Coding Interview (Step-by-Step)

How to Explain Best Time to Buy and Sell Stock in a Coding Interview (Step-by-Step)

Best Time to Buy and Sell Stock is a deceptively simple problem. The brute force is obvious, but the optimal O(n) solution requires a clear mental model — track the minimum price seen so far, and at every step ask: “what’s the best profit I can make if I sell today?”

In this post, you’ll learn exactly how to walk an interviewer through this problem: the core insight, the sliding window framing, a full step-by-step trace, and the edge cases that catch candidates off guard.


Problem Statement

LeetCode 121 Easy

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximise your profit by choosing a single day to buy and a different future day to sell. Return the maximum profit you can achieve. If you cannot achieve any profit, return 0.

Examples

Example 1
Input: prices = [7, 1, 5, 3, 6, 4]
Output: 5
Explanation: Buy on day 2 (price=1), sell on day 5 (price=6) → profit = 6 − 1 = 5
Example 2
Input: prices = [7, 6, 4, 3, 1]
Output: 0
Explanation: Prices only decrease — no profitable transaction possible

Constraints

  • 1 <= prices.length <= 10⁵
  • 0 <= prices[i] <= 10⁴

What Is the Problem?

“I need to find the maximum difference between two elements in the array where the smaller element comes first — that’s the best buy price followed by the best sell price. If prices only decrease, no profitable transaction exists and I return 0.”

Framing it as a “maximum difference with order constraint” immediately points toward the single-pass greedy approach.


Step 1: Start With the Brute Force (Then Dismiss It)

❌ Brute Force

Try every buy/sell pair — two nested loops

Time: O(n²)

Space: O(1)

Too slow for n = 10⁵

✅ Single Pass (Greedy)

Track min price so far, update max profit at each step

Time: O(n)

Space: O(1)

One pass — optimal


The Key Insight

💡 Core Insight

To maximise profit when selling on day i, we want to have bought at the lowest price seen before day i. So we track the running minimum as we scan left to right. At each price, we ask: “if I sell today, what’s my profit given the cheapest buy price I’ve seen so far?”

This is also framed as a sliding window problem — the left pointer marks the buy day (the current minimum), and the right pointer is the sell day scanning forward. When we find a new minimum, we move the left pointer there.


Step 2: Explain the Algorithm in Plain English

“I initialise min_price to infinity and max_profit to 0. I scan through each price. If the current price is lower than min_price, I update min_price — I’ve found a better buy day. Otherwise I compute today’s profit as price - min_price and update max_profit if it’s better. At the end, max_profit holds the answer.”

Step 3: Talk Through the Code

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_price  = float('inf')  # Best buy price seen so far
        max_profit = 0             # Best profit seen so far

        for price in prices:
            if price < min_price:
                min_price = price          # Found a cheaper buy day — update
            else:
                profit = price - min_price # What if we sell today?
                max_profit = max(max_profit, profit)

        return max_profit

Point out float('inf') as the initial min_price — ensures the first real price always sets the minimum without needing a special case.


Visual Walkthrough

Tracing through prices = [7, 1, 5, 3, 6, 4]:

Price chart — buy at day 2 (price=1), sell at day 5 (price=6) → profit = 5
7
Day 1
1
BUY★
5
Day 3
3
Day 4
6
SELL★
4
Day 6
Buy day (min price)
Sell day (max profit)
Other days
✅ Max profit = 6 − 1 = 5 (buy day 2, sell day 5)

Step-by-step pointer trace:

DayPricemin_priceProfit Todaymax_profitAction
1770New min → update min_price
2110New min → update min_price
35144Profit = 5−1=4 → update max
43124Profit = 3−1=2 → no update
56155Profit = 6−1=5 → update max ★
64135Profit = 4−1=3 → no update

Yellow rows = new minimum found. Green row = new max profit found.


Step 4: Highlight Edge Cases

1 Prices only decrease
"e.g. [7, 6, 4, 3, 1] — every new price becomes the new minimum. We never enter the else branch with a positive profit. max_profit stays 0 and we return 0. Correct."
2 Single element array
"With only one price, there's no sell day — we can't make a transaction. The loop runs once, sets min_price, but never computes a profit. We return 0. Correct."
3 All prices the same
"e.g. [5, 5, 5] — profit is always 5 - 5 = 0 so max_profit stays 0. We return 0 — correct, no gain possible."
4 Max profit at the very end
"e.g. [1, 2, 3, 4, 5] — the best transaction is buy on day 1, sell on day 5. The loop correctly tracks profit at every step and captures the peak at the last element."

Step 5: State Time and Space Complexity

ApproachTimeSpace
Brute Force O(n²) O(1)
Single Pass ✓ O(n) O(1)
"A single left-to-right scan — each price is visited exactly once. We track only two variables regardless of input size, so space is O(1)."

Interview Checklist for Best Time to Buy and Sell Stock

  • Restate — "find max difference where smaller element comes before larger"
  • Call out the constraint — you must buy before you sell
  • Mention brute force O(n²) and dismiss it
  • State the key insight — track min price so far, compute profit at each step
  • Mention the sliding window framing — left = buy day, right = sell day
  • Explain why float('inf') is used as initial min_price
  • Handle decreasing prices — return 0, not a negative number
  • Handle single element — no transaction possible, return 0
  • State O(n) time and O(1) space
  • Ask before coding, don't just dive in

If you can solve Best Time to Buy and Sell Stock cleanly, try these next:

💡 Practicing your explanations out loud is just as important as writing correct code. The best candidates aren't the ones who solve it fastest — they're the ones who make the interviewer feel like they're thinking alongside them.
Scroll to Top