LeetCode 121: Best Time to Buy and Sell Stock is an Easy array / string problem. This Python walkthrough develops a running minimum solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Easy |
|---|---|
| Topic | Array / String |
| Reusable pattern | running minimum |
| Complexity | O(n) time and O(1) extra space |
Recognizing the pattern
Array and string questions usually reward a precise index invariant. Decide which prefix or suffix is already final before mutating the next position.
For this problem specifically, track the cheapest price seen before today and the best profit from selling today or earlier. The invariant worth writing beside the code is: The minimum is the best legal buy price for the current sell day.
Step-by-step algorithm
- Identify the input state consumed by
maxProfit(prices)and initialize the data required by the running minimum pattern. - Track the cheapest price seen before today and the best profit from selling today or earlier.
- After each update, verify the page’s central invariant: The minimum is the best legal buy price for the current sell day.
- Finish only after the boundary behavior is covered: Descending prices return zero; the buy must occur before the sale.
Python solution
class Solution:
def maxProfit(self, prices):
cheapest, best = float("inf"), 0
for price in prices:
cheapest = min(cheapest, price)
best = max(best, price - cheapest)
return bestReading the implementation
The main entry point is maxProfit(prices). The named working state includes cheapest, best; those variables make the running minimum state visible instead of hiding it in incidental control flow.
A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, track the cheapest price seen before today and the best profit from selling today or earlier.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Track the cheapest price seen before today and the best profit from selling today or earlier. Each update records the current item without invalidating earlier decisions; consequently, the minimum is the best legal buy price for the current sell day.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(n) time and O(1) extra space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
A copied output buffer can simplify reasoning, but the in-place version reduces auxiliary memory when mutation is allowed. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().maxProfit([7,1,5,3,6,4]) == 5Common mistakes and edge cases
- Problem-specific boundary: Descending prices return zero; the buy must occur before the sale.
- Pattern-level pitfall: Do not let a write operation destroy input that a later read still needs; write direction and boundary conventions matter.
- Invariant check: after every update, confirm that the minimum is the best legal buy price for the current sell day.
Interview review checklist
- Explain why running minimum matches the structure of this input.
- State the invariant in one sentence before tracing code: The minimum is the best legal buy price for the current sell day.
- Derive O(n) time and O(1) extra space from how many times each element or state is visited.
- Test the boundary explicitly: Descending prices return zero; the buy must occur before the sale.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 189. Rotate Array · Next: 122. Best Time to Buy and Sell Stock II