Python 0123.py
class Solution:
def maxProfit(self, prices: List[int]) -> int:
dp = [ [ 0, None ]] # realized profit, ongoing transaction
result = 0
for current in prices:
next = set()
for check in dp:
if check[1] == None:
next.add(tuple(check))
next.add(tuple([ check[0], current ])) # new TX
continue
if check[1] >= current:
next.add(tuple([ check[0], current ])) # improved TX
else:
next.add(tuple(check)) # keep it open
# and close it, too
gain = current - check[1]
if check[0] == 0:
next.add(tuple([ gain, None ])) # start second TX
total = check[0] + gain
result = max(result, total)
# prune: select best
bestClosed = 0
bestOpen0 = 0
bestOpen1 = 0
for check in next:
if check[1] == None:
bestClosed = max(bestClosed, check[0])
else:
potential = check[0] + current - check[1]
if check[0] == 0:
bestOpen0 = max(bestOpen0, potential)
else:
bestOpen1 = max(bestOpen1, potential)
dp = set()
dp.add(tuple([ 0, None ]))
for check in next:
if check[1] == None:
if check[0] == bestClosed:
dp.add(check)
else:
potential = check[0] + current - check[1]
if check[0] == 0:
if potential == bestOpen0:
dp.add(check)
else:
if potential == bestOpen1:
dp.add(check)
bestOpen1 += 1 # skip if identical follow
return result
Difficulty
and has an acceptance rate of about 54% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the classic “best time to buy and sell stock with at most two transactions” problem. It maintains a dynamic-programming state that captures both realized profit and the price of an ongoing transaction (if any). By iterating through the price list once, it updates possible states, prunes sub-optimal ones, and records the maximum profit achievable.
Core Logic
Initialization
The algorithm starts with a single DP entry representing no profit and no open transaction.
dp = [ [ 0, None ]] # realized profit, ongoing transaction
result = 0
Iterating Over Prices
For each price in the input list, a new collection next is built to hold candidate states derived from the current DP set.
for current in prices:
next = set()
for check in dp:
...
Expanding States
If a state has no open transaction (check[1] == None), two possibilities are added to next: keeping the state unchanged and opening a new transaction at the current price.
if check[1] == None:
next.add(tuple(check))
next.add(tuple([ check[0], current ])) # new transaction
continue
When a transaction is already open, the code distinguishes two scenarios:
- The current price is lower or equal to the purchase price, meaning the transaction can be improved by resetting the buy price.
if check[1] >= current:
next.add(tuple([ check[0], current ])) # improved transaction
- The current price is higher, allowing the transaction to stay open, to be closed, or to start a second transaction after closing the first.
else:
next.add(tuple(check)) # keep it open
gain = current - check[1] # profit from closing
if check[0] == 0:
next.add(tuple([ gain, None ])) # start second transaction
total = check[0] + gain
result = max(result, total)
Pruning Sub-optimal States
After generating all candidates, the algorithm computes three “best” metrics: the highest profit among closed states, the highest potential profit for a first open transaction, and the highest potential profit for a second open transaction.
bestClosed = 0
bestOpen0 = 0
bestOpen1 = 0
for check in next:
if check[1] == None:
bestClosed = max(bestClosed, check[0])
else:
potential = check[0] + current - check[1]
if check[0] == 0:
bestOpen0 = max(bestOpen0, potential)
else:
bestOpen1 = max(bestOpen1, potential)
Only states that achieve these best values are retained for the next iteration, dramatically reducing the number of states that must be examined.
dp = set()
dp.add(tuple([ 0, None ]))
for check in next:
if check[1] == None:
if check[0] == bestClosed:
dp.add(check)
else:
potential = check[0] + current - check[1]
if check[0] == 0:
if potential == bestOpen0:
dp.add(check)
else:
if potential == bestOpen1:
dp.add(check)
bestOpen1 += 1 # skip if identical follow
Final Result
The variable result accumulates the maximum profit observed whenever a transaction is closed. After processing all prices, result is returned.
return result
Edge Cases Handled
The algorithm gracefully handles an empty price list: the loop body never executes, leaving result at its initial value of zero.
When prices are strictly decreasing, no profitable transaction can be formed; the state never transitions to a closed profit greater than zero, and the final result remains zero.
Equal consecutive prices are treated as non-profitable moves; the open transaction can be updated to the same price without affecting profit calculations.
The code also supports the scenario where the first transaction yields zero profit (e.g., buying and selling at the same price) and a second profitable transaction follows, because the check if check[0] == 0 allows a new transaction to start after a zero-profit closure.
Performance Optimizations
State deduplication is achieved by storing DP entries in a set of tuples, ensuring that identical configurations are merged automatically.
The pruning step discards any state that does not match the best closed profit or the best potential for an open transaction, limiting the DP size to a constant number of entries regardless of input length.
Potential profit for an open transaction is computed once per candidate (potential = check[0] + current - check[1]) and reused for both pruning and result updates, avoiding redundant arithmetic.
By updating result only when a transaction is closed, the algorithm avoids unnecessary comparisons for states that remain open.
Overall, the combination of set-based deduplication, aggressive pruning, and reuse of intermediate calculations yields a solution that processes the input in a single pass with a bounded amount of work per price.
ELI5 - Simplified Explanation
Imagine you are at a toy shop where the prices of your favorite building blocks change every single day. This code is like a smart little robot that wants to help you save the most money. The robot watches the price tag on the blocks as it changes throughout the week.
First, the robot keeps track of two things. It remembers how much money you already saved, and it remembers if you are currently holding onto a set of blocks you bought earlier.
Every day, when the robot looks at the new price, it makes a few guesses about what to do. If you have no blocks in your hand, the robot thinks about whether today is a good day to buy some. It looks at the price tag and decides if it is low enough to start a deal. If you are already holding blocks, the robot thinks about whether you should keep holding them to see if the price goes higher, or if you should sell them right now to finish your deal and keep the difference as profit.
The robot is very careful about making sure it only remembers the very best ways to make money, so it throws away any plans that would leave you with less coins. After checking all of the possibilities for every day until the end of the week, the robot knows exactly how much money you have earned by buying and selling at the right times. It is all about finding the best moments to jump in and out of the toy market to keep your piggy bank as full as possible.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | Python | C++ | Java | TS | |||||||
| WalkCCC | Python | C++ | Java | |||||||||
| leetcode.ca | Python | C++ | C# | Rust | Java | Go | TS | |||||
| LeetcodeHelp | Python | C++ | Java | |||||||||
| MemoryLimitExceeded | Python | C++ | ||||||||||
| Progiez | Python | C++ | Java | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JS | |||||||||||
| FelixFan1122 | C# | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| martianoff | Scala | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| vli02 | C | |||||||||||
| wisdompeak | Python | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | Python, Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JavaScript | |||||||||||
| FelixFan1122 | C# | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| martianoff | Scala | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| vli02 | C | |||||||||||
| wisdompeak | Python | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 122: Best Time to Buy and Sell Stock II
- problem 188: Best Time to Buy and Sell Stock IV
- problem 689: Maximum Sum of 3 Non-Overlapping Subarrays
Solved On The Same Day
- problem 108: Convert Sorted Array to Binary Search Tree
- problem 482: License Key Formatting
- problem 72: Edit Distance
- problem 122: Best Time to Buy and Sell Stock II
- problem 167: Two Sum II - Input Array Is Sorted
- problem 453: Minimum Moves to Equal Array Elements
- problem 515: Find Largest Value in Each Tree Row
- problem 535: Encode and Decode TinyURL
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality