Problem 188

Abstract / Summary

Given a maximum number of transactions, find the best profit from buying and selling stock multiple times.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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())
31 lines | 1076 bytes | submitted August 29, 2023 | GitHub   22% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 51% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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())
written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 4 | μ = 4.77 | σ = 1.83

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
43 links | 28 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Sliding Window: Best Time to Buy and Sell Stock - Leetcode 121 - Python'
NeetCode 9 mins
Sliding Window: Best Time to Buy and Sell Stock - Leetcode 121 - Python
YouTube video 'Best Time to BUY and SELL STOCK | Leetcode | C++ | Java | Brute-Optimal'
take U forward 7 mins
Best Time to BUY and SELL STOCK | Leetcode | C++ | Java | Brute-Optimal
YouTube video 'Best Time to Buy and Sell Stock with Cooldown - Leetcode 309 - Python'
NeetCode 16 mins
Best Time to Buy and Sell Stock with Cooldown - Leetcode 309 - Python
YouTube video 'Best Time to Buy and Sell Stock with Cooldown - Leetcode 309 - Python'
NeetCode 16 mins
Best Time to Buy and Sell Stock with Cooldown - Leetcode 309 - Python
YouTube video 'Best time to buy and sell stock 4 | Leetcode #188'
Techdose 33 mins
Best time to buy and sell stock 4 | Leetcode #188
YouTube video 'Leetcode 188. Best Time to Buy and Sell Stock IV [ Algorithm + Code Explained]'
jayati tiwari 13 mins
Leetcode 188. Best Time to Buy and Sell Stock IV [ Algorithm + Code Explained]
YouTube video 'Best Time to Buy and Sell Stock IV | Live Coding with Explanation | Leetcode - 188'
Algorithms Made Easy 27 mins
Best Time to Buy and Sell Stock IV | Live Coding with Explanation | Leetcode - 188
YouTube video 'Leetcode - Best Time to Buy and Sell Stock IV (Python)'
Timothy H Chang 11 mins
Leetcode - Best Time to Buy and Sell Stock IV (Python)
YouTube video 'Leetcode 188. Best Time to Buy and Sell Stock IV'
Fraz 11 mins
Leetcode 188. Best Time to Buy and Sell Stock IV
YouTube video 'best time to buy and sell stock iv leetcode | leetcode 188'
Naresh Gupta 18 mins
best time to buy and sell stock iv leetcode | leetcode 188
YouTube video '3573. Best Time to Buy and Sell Stock V | Leetcode Daily - Python'
Leetcode Daily 11 mins
3573. Best Time to Buy and Sell Stock V | Leetcode Daily - Python
YouTube video 'LeetCode 188. Best Time to Buy and Sell Stock IV'
Happy Coding 28 mins
LeetCode 188. Best Time to Buy and Sell Stock IV
YouTube video 'Leetcode 188 Best Time to Buy and Sell Stock IV | DP | Coding Decoded SDE Sheet'
Coding Decoded 10 mins
Leetcode 188 Best Time to Buy and Sell Stock IV | DP | Coding Decoded SDE Sheet
YouTube video 'Daily Leetcode #893: Sep 10, 2022 - 188. Best Time to Buy and Sell Stock IV'
Programming Live with Larry 21 mins
Daily Leetcode #893: Sep 10, 2022 - 188. Best Time to Buy and Sell Stock IV
YouTube video 'Best Time to Buy and Sell Stock I,II,III,IV,Cool down and Transaction Fee | One common solution'
Coders Camp 24 mins
Best Time to Buy and Sell Stock I,II,III,IV,Cool down and Transaction Fee | One common solution
YouTube video 'Daily Leetcode #201: Oct 18, 2020 - 188. Best Time to Buy and Sell Stock IV'
Programming Live with Larry 68 mins
Daily Leetcode #201: Oct 18, 2020 - 188. Best Time to Buy and Sell Stock IV
YouTube video 'Best Time to Buy and Sell Stock II , III , IV  || DYNAMIC PROGRAMMING | LEETCODE HARD'
code Explainer 18 mins
Best Time to Buy and Sell Stock II , III , IV || DYNAMIC PROGRAMMING | LEETCODE HARD
YouTube video 'Google Coding Interview Question | Leetcode 188 | Best Time to Buy and Sell Stock IV'
WorkWithGoogler 11 mins
Google Coding Interview Question | Leetcode 188 | Best Time to Buy and Sell Stock IV
YouTube video '188. Best Time to Buy and Sell Stock IV || Hard  || State DP || Cpp'
Komal Pal 28 mins
188. Best Time to Buy and Sell Stock IV || Hard || State DP || Cpp
YouTube video 'LeetCode 188 | Best Time to Buy and Sell Stock IV | Dynamic Programming | Java'
Sleepy Cracker 6 mins
LeetCode 188 | Best Time to Buy and Sell Stock IV | Dynamic Programming | Java
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

10 solutions   August 29, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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