Learning Outcome
After this lesson, you should be able to convert the "choose buy and sell days" brute force into a one-pass greedy scan.
Problem Statement
Given prices, where prices[i] is the stock price on day i, return the maximum profit from one buy and one later sell. If no profit is possible, return 0.
| Input | Output | Why |
|---|---|---|
[7, 1, 5, 3, 6, 4] | 5 | Buy at 1, sell at 6. |
Brute Force Approach
Try every buy day and every later sell day. Compute prices[sell] - prices[buy] and keep the best profit.
This checks the rule correctly, but it costs O(n^2) because every day can be paired with many later days.
Optimized Approach
While scanning left to right, keep the minimum price seen so far. If you sell today, the best valid buy day must be one of the earlier days, so today profit is price - minPrice.
This works because every sell day only needs the cheapest earlier buy day, not all earlier days.
Exact Pseudocode
minPrice = infinity
best = 0
for price in prices:
minPrice = min(minPrice, price)
best = max(best, price - minPrice)
return best
Reference Code
class Solution:
def maxProfit(self, prices):
min_price = float("inf")
best = 0
for price in prices:
min_price = min(min_price, price)
best = max(best, price - min_price)
return bestSample Dry Run
| price | minPrice | profit if sold today | best |
|---|---|---|---|
| 7 | 7 | 0 | 0 |
| 1 | 1 | 0 | 0 |
| 5 | 1 | 4 | 4 |
| 3 | 1 | 2 | 4 |
| 6 | 1 | 5 | 5 |
| 4 | 1 | 3 | 5 |
Complexity
| Measure | Value | Reason |
|---|---|---|
| Time | O(n) | One scan over all prices. |
| Space | O(1) | Only two variables are stored. |
Edge Cases
- Prices always decrease, such as
[7, 6, 4, 3, 1]. - Only one day or empty input if allowed by platform constraints.
- Best buy day appears before the best sell day, not after.
Interview Checklist
- Emphasize "buy before sell".
- Track the cheapest price seen so far.
- Return
0when no positive profit exists.
FAQs
Why is this greedy?
For each sell day, the best decision only depends on the cheapest valid buy day seen before it.
Can I sell before buying?
No. The left-to-right scan enforces that the buy price comes from an earlier day.
What if all prices fall?
The best profit remains 0.