LeetCode 122: Best Time to Buy and Sell Stock II is a Medium array / string problem. This Python walkthrough develops a greedy positive differences 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 | Medium |
|---|---|
| Topic | Array / String |
| Reusable pattern | greedy positive differences |
| 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, add every positive day-to-day increase. Each rising run contributes the same profit as buying at its start and selling at its end. The invariant worth writing beside the code is: Accumulated profit equals the maximum realizable profit over processed days with no overlapping positions.
Step-by-step algorithm
- Identify the input state consumed by
maxProfit(prices)and initialize the data required by the greedy positive differences pattern. - Add every positive day-to-day increase. Each rising run contributes the same profit as buying at its start and selling at its end.
- After each update, verify the page’s central invariant: Accumulated profit equals the maximum realizable profit over processed days with no overlapping positions.
- Finish only after the boundary behavior is covered: Flat and falling transitions contribute nothing.
Python solution
class Solution:
def maxProfit(self, prices):
return sum(max(0, prices[i] - prices[i - 1]) for i in range(1, len(prices)))Reading the implementation
The main entry point is maxProfit(prices). The implementation keeps little named state because each operation can be resolved directly from the current input position.
The method expresses the transformation directly without a general traversal loop. In concrete terms, add every positive day-to-day increase. Each rising run contributes the same profit as buying at its start and selling at its end.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Add every positive day-to-day increase. Each rising run contributes the same profit as buying at its start and selling at its end. Each update records the current item without invalidating earlier decisions; consequently, accumulated profit equals the maximum realizable profit over processed days with no overlapping positions.
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]) == 7Common mistakes and edge cases
- Problem-specific boundary: Flat and falling transitions contribute nothing.
- 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 accumulated profit equals the maximum realizable profit over processed days with no overlapping positions.
Interview review checklist
- Explain why greedy positive differences matches the structure of this input.
- State the invariant in one sentence before tracing code: Accumulated profit equals the maximum realizable profit over processed days with no overlapping positions.
- Derive O(n) time and O(1) extra space from how many times each element or state is visited.
- Test the boundary explicitly: Flat and falling transitions contribute nothing.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 121. Best Time to Buy and Sell Stock · Next: 55. Jump Game