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
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
Output: 5
Explanation: Buy on day 2 (price=1), sell on day 5 (price=6) → profit = 6 − 1 = 5
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)
Try every buy/sell pair — two nested loops
Time: O(n²)
Space: O(1)
Too slow for n = 10⁵
Track min price so far, update max profit at each step
Time: O(n)
Space: O(1)
One pass — optimal
The Key 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 initialisemin_priceto infinity andmax_profitto 0. I scan through each price. If the current price is lower thanmin_price, I updatemin_price— I’ve found a better buy day. Otherwise I compute today’s profit asprice - min_priceand updatemax_profitif it’s better. At the end,max_profitholds 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]:
Step-by-step pointer trace:
| Day | Price | min_price | Profit Today | max_profit | Action |
|---|---|---|---|---|---|
| 1 | 7 | 7 | — | 0 | New min → update min_price |
| 2 | 1 | 1 | — | 0 | New min → update min_price |
| 3 | 5 | 1 | 4 | 4 | Profit = 5−1=4 → update max |
| 4 | 3 | 1 | 2 | 4 | Profit = 3−1=2 → no update |
| 5 | 6 | 1 | 5 | 5 | Profit = 6−1=5 → update max ★ |
| 6 | 4 | 1 | 3 | 5 | Profit = 4−1=3 → no update |
Yellow rows = new minimum found. Green row = new max profit found.
Step 4: Highlight Edge Cases
"e.g.[7, 6, 4, 3, 1]— every new price becomes the new minimum. We never enter theelsebranch with a positive profit.max_profitstays 0 and we return 0. Correct."
"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."
"e.g.[5, 5, 5]— profit is always5 - 5 = 0somax_profitstays 0. We return 0 — correct, no gain possible."
"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
| Approach | Time | Space |
|---|---|---|
| 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
Related Problems to Practice
If you can solve Best Time to Buy and Sell Stock cleanly, try these next:
