Problem 123

Abstract / Summary

Find the best profit from at most two buy and sell transactions with a given array of stock prices.

Note

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

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
59 lines | 2121 bytes | submitted August 21, 2023 | GitHub   16% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 54% (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 “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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 3 | μ = 3.93 | σ = 1.90

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 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
50 links | 34 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'LeetCode Best Time to Buy and Sell Stock Solution Explained - Java'
Nick White 4 mins
LeetCode Best Time to Buy and Sell Stock Solution Explained - Java
YouTube video 'Best Time to Buy and Sell Stock III | Leet code 123 | Theory explained + Python code'
Sai Anish Malla 16 mins
Best Time to Buy and Sell Stock III | Leet code 123 | Theory explained + Python code
YouTube video 'Best Time to Buy and Sell Stock iii | LeetCode 123 | C++, Java, Python'
Knowledge Center 21 mins
Best Time to Buy and Sell Stock iii | LeetCode 123 | C++, Java, Python
YouTube video 'Best Time to Buy and Sell Stock III | Live Coding with Explanation | Leetcode - 123'
Algorithms Made Easy 27 mins
Best Time to Buy and Sell Stock III | Live Coding with Explanation | Leetcode - 123
YouTube video 'best time to buy and sell stock iii leetcode | best time to buy and sell stock 3 | leetcode 123'
Naresh Gupta 15 mins
best time to buy and sell stock iii leetcode | best time to buy and sell stock 3 | leetcode 123
YouTube video 'Best Time to Buy and Sell Stock III | Leetcode 123 | Leetcode Hard | Live coding session🔥🔥🔥🔥'
Coding Decoded 3 mins
Best Time to Buy and Sell Stock III | Leetcode 123 | Leetcode Hard | Live coding session🔥🔥🔥🔥
YouTube video '[Complete Series] Best Time to Buy and Sell Stock | LeetCode | Recursion & DP Solution, Explained'
Tanishq Chaudhary 27 mins
[Complete Series] Best Time to Buy and Sell Stock | LeetCode | Recursion & DP Solution, Explained
YouTube video 'Best Time to Buy and Sell Stock III | Leetcode August Challenge (Day16) | Leetcode 123 🔥🔥🔥'
Coding Decoded 13 mins
Best Time to Buy and Sell Stock III | Leetcode August Challenge (Day16) | Leetcode 123 🔥🔥🔥
YouTube video 'Best Time to Buy and Sell Stock III/IV: Leetcode 123/188'
Tony Teaches 10 mins
Best Time to Buy and Sell Stock III/IV: Leetcode 123/188
YouTube video 'LeetCode All Best Time to Buy and Sell Stock Questions'
happygirlzt 23 mins
LeetCode All Best Time to Buy and Sell Stock Questions
YouTube video 'Daily Leetcode #564: Oct 16, 2021 - 123. Best Time to Buy and Sell Stock III'
Programming Live with Larry 22 mins
Daily Leetcode #564: Oct 16, 2021 - 123. Best Time to Buy and Sell Stock III
YouTube video 'Daily Leetcode #138: Aug 16, 2020 - 123. Best Time to Buy and Sell Stock III'
Programming Live with Larry 13 mins
Daily Leetcode #138: Aug 16, 2020 - 123. Best Time to Buy and Sell Stock III
YouTube video '123. Best Time to Buy and Sell Stock III | Leetcode'
Cherry Coding [IIT-G] 14 mins
123. Best Time to Buy and Sell Stock III | Leetcode
YouTube video 'Day 292: LeetCode Problem 123. Best Time to Buy and Sell Stock III - Swift'
iOSxBank 12 mins
Day 292: LeetCode Problem 123. Best Time to Buy and Sell Stock III - Swift
YouTube video 'Amazon Coding Interview Question | Leetcode 123 | Best Time to Buy and Sell Stock III'
WorkWithGoogler 6 mins
Amazon Coding Interview Question | Leetcode 123 | Best Time to Buy and Sell Stock III
YouTube video 'leetcode 123. Best Time to Buy and Sell Stock III - DP; Video-4 of Leetcode stock buy/sell problems'
Code-Yao 20 mins
leetcode 123. Best Time to Buy and Sell Stock III - DP; Video-4 of Leetcode stock buy/sell problems
YouTube video 'LeetCode 123 | Best Time to Buy and Sell Stock III | Array | Java'
Sleepy Cracker 5 mins
LeetCode 123 | Best Time to Buy and Sell Stock III | Array | Java
YouTube video 'Leetcode Question 123 "Best Time to Buy and Sell Stock III" in Python'
Ghumman Tech 8 mins
Leetcode Question 123 "Best Time to Buy and Sell Stock III" in Python
YouTube video 'Best Time to Buy and Sell Stock III, Hard, C++, LeetCode (Another look!)'
H William Polenz 217 mins
Best Time to Buy and Sell Stock III, Hard, C++, LeetCode (Another look!)
19 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

9 solutions   August 21, 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