Python 0188.py
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
dp = defaultdict(int) # positive index i: have stocks, it's the i-th transaction
# negative index i: no stocks, finished i transactions
dp[0] = 0
for p in prices:
# do nothing
next = dp.copy()
for tx in sorted(dp.keys()):
if tx >= k:
continue
flip = -tx
if tx >= 0:
# buy
if flip - 1 in dp:
next[flip - 1] = max(dp[flip - 1], dp[tx] - p)
else:
next[flip - 1] = dp[tx] - p
else:
# sell
if flip in dp:
next[flip] = max(next[flip], dp[tx] + p)
else:
next[flip] = dp[tx] + p
dp = next
return max(dp.values())
Difficulty
and has an acceptance rate of about 51% (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 “at most k transactions” stock-profit problem using dynamic programming. It encodes the state of each possible transaction in a dictionary where the sign of the key distinguishes between holding a stock (positive) and having completed a transaction without holding (negative). By iterating through the price list once and updating this dictionary, the algorithm accumulates the best achievable profit for every admissible transaction count.
Initialization
At the start a dictionary dp is created with a default integer value of 0. The entry dp[0] = 0 represents the baseline state: zero completed transactions and no stock held, with zero profit. The use of defaultdict(int) ensures that any missing key automatically yields a profit of 0, simplifying later look-ups.
dp = defaultdict(int) # positive index i: have stocks, it's the i-th transaction
# negative index i: no stocks, finished i transactions
dp[0] = 0
Iteration over Prices
The core loop processes each price p from the input list. For each price a fresh copy of the current state dictionary is made, named next. This copy preserves the option of “doing nothing” for the current day, because any state not explicitly updated will retain its previous profit value.
for p in prices:
# do nothing
next = dp.copy()
Transaction State Updates
Inside the price loop, the algorithm walks through all existing transaction keys in sorted order. The sorting guarantees deterministic processing, which is important because the sign-based encoding can generate both positive and negative keys.
For each key tx the algorithm first discards any state that already reached the maximum allowed number of transactions (tx >= k). This early exit prevents unnecessary work for states that cannot be extended further.
for tx in sorted(dp.keys()):
if tx >= k:
continue
The variable flip = -tx flips the sign of the current key, turning a “holding” state into its corresponding “not holding” state and vice-versa.
When tx is non-negative, the algorithm interprets the state as currently holding a stock that belongs to the tx-th transaction. The only feasible action is to buy a new stock, which moves the state to flip - 1 (one more transaction started, now holding). The profit is updated by subtracting the current price. If the target state already exists, the maximum of the existing profit and the new candidate profit is kept; otherwise the new profit is stored directly.
if tx >= 0:
# buy
if flip - 1 in dp:
next[flip - 1] = max(dp[flip - 1], dp[tx] - p)
else:
next[flip - 1] = dp[tx] - p
When tx is negative, the state represents not holding any stock after completing -tx transactions. The only legal move is to sell a previously bought stock, which transitions to the positive key flip. The profit is increased by the current price, and the same max-update logic applies.
else:
# sell
if flip in dp:
next[flip] = max(next[flip], dp[tx] + p)
else:
next[flip] = dp[tx] + p
After all possible updates for the current price are processed, the dp reference is replaced with the next dictionary, ready for the next iteration.
dp = next
Edge Cases Handled
The algorithm gracefully handles an empty price list because the outer loop simply never executes, leaving dp with its initial entry 0. Consequently the final max(dp.values()) returns 0, which is the correct profit when no trading is possible.
When the transaction limit k is zero, the early continue condition (tx >= k) immediately skips any state updates, again resulting in a profit of 0.
The sign-based encoding also implicitly manages the situation where a sell operation is attempted without a preceding buy: such a transition would require a positive key that does not exist in dp, and the code only creates a new state when the corresponding source state is present, thereby avoiding invalid profit calculations.
Performance Optimizations
A notable optimization is the compact representation of both “holding” and “not holding” states within a single dictionary using signed keys. This eliminates the need for a two-dimensional DP table and reduces memory overhead.
Copying the dictionary for each price (next = dp.copy()) enables constant-time “do nothing” handling without extra condition checks inside the inner loop.
The early continue when the transaction count reaches the limit prevents the inner loop from exploring states that cannot contribute to a better solution, cutting down unnecessary iterations.
Finally, the use of defaultdict(int) removes explicit existence checks for many keys, allowing the code to fall back to a zero profit baseline automatically, which streamlines the update logic.
Result Extraction
After processing all prices, the algorithm extracts the maximum profit across all stored states. Because the dictionary contains both holding and non-holding states, taking the global maximum ensures that the best achievable profit is returned regardless of whether the final day ends with a stock still held or not.
return max(dp.values()) ELI5 - Simplified Explanation
Imagine you are at a market that sells special magical toys. Each day, the price of these toys goes up or down. You want to buy a toy when it is cheap and sell it when it is expensive to collect as many gold coins as possible. You are only allowed to make a certain number of these trades, which is called k here.
The code keeps a treasure chest called dp. Inside this chest, it remembers how many gold coins you have depending on whether you are currently holding a toy or if you have finished a sale. Positive numbers in the chest represent times you have a toy in your hand, and negative numbers represent times you have successfully sold one.
Every day, the computer looks at the price of the toy. It creates a new list called next to see what happens if you decide to do a new action. It looks at all the different situations you have been in before. If you have a toy, you might decide to sell it to get gold coins. If you do not have a toy, you might decide to buy one using the gold coins you already have.
It carefully checks every possibility to make sure you always have the most gold coins possible. After deciding whether to buy, sell, or wait on that specific day, it updates the treasure chest. By the time it looks at every price on every day, the treasure chest shows exactly how much gold you managed to get from all your smart trading.
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 | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | C# | Go | TS | |||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | aylei | Rust | |||||||||
| begeekmyfriend | C | ||||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JS | ||||||||||
| FelixFan1122 | C# | ||||||||||
| gaosq0604 | Python | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| aylei | Rust | ||||||||||
| begeekmyfriend | C | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JavaScript | ||||||||||
| FelixFan1122 | C# | ||||||||||
| gaosq0604 | Python | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin |
Videos
Similar Problems
- problem 121: Best Time to Buy and Sell Stock
- problem 122: Best Time to Buy and Sell Stock II
- problem 123: Best Time to Buy and Sell Stock III
Solved On The Same Day
- problem 71: Simplify Path
- problem 309: Best Time to Buy and Sell Stock with Cooldown
- problem 516: Longest Palindromic Subsequence
- problem 673: Number of Longest Increasing Subsequence
- problem 712: Minimum ASCII Delete Sum for Two Strings
- problem 714: Best Time to Buy and Sell Stock with Transaction Fee
- problem 740: Delete and Earn
- problem 931: Minimum Falling Path Sum
- problem 2483: Minimum Penalty for a Shop
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