Loading…
Best Time to Buy and Sell Stock is a easy coding interview question covering arrays, greedy — the kind asked at FAANG (Facebook/Meta, Apple, Amazon, Netflix, Google) and AI-first companies like Anthropic, OpenAI, and Nvidia.
Given an array prices where prices[i] is the stock price on day i, find the maximum profit from one buy and one sell. You must buy before you sell. Return 0 if no profit is possible.
Example: [7,1,5,3,6,4] -> 5 (buy at 1, sell at 6) Example: [7,6,4,3,1] -> 0 (prices only fall)
Try it yourself first
In an interview you'd get about 15 minutes for a easy question. Sketch an approach before peeking — struggling is where the learning happens.
Stuck? Reveal them one at a time — each hint gives away a little more.
Ready to compare notes? The full solution, visualization, and complexity analysis are below.
Single-pass greedy: track the minimum price seen so far. At each price, compute the profit if you sold today (price - min_price) and update the running maximum. Never sell before buying — the minimum is always updated before computing profit.
| 1 | def max_profit(prices: list[int]) -> int: |
| ▶ | min_price = float('inf') |
| ▶ | max_profit = 0 |
| 4 | for price in prices: |
| 5 | if price < min_price: |
| 6 | min_price = price |
| 7 | elif price - min_price > max_profit: |
| 8 | max_profit = price - min_price |
| 9 | return max_profit |
i=0 (7): min_price=7, max_profit=0.
Key Insights
A full interview loop is more than one round. These are the others, each with what is on the site for it.