Python 0714.py
class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
dp = [ 0, -99999999 ] # 0 => wealth, own no stock, 1 => # wealth owning stock
for p in prices:
next = [ 0, 0 ]
next[0] = max(dp[0], dp[1] + p)
next[1] = max(dp[1], dp[0] - p - fee)
dp = next
return dp[0]
Difficulty
and has an acceptance rate of about 72% (800k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
- Greedy
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 “stock trading with transaction fee” problem. It computes the maximum achievable profit from a sequence of daily stock prices while accounting for a fixed fee charged on each purchase. The algorithm walks through the price list once, maintaining two state variables that capture the best possible wealth when the trader holds no stock and when the trader holds one stock. By updating these states iteratively, the final wealth without any holding yields the optimal profit.
Core Logic
Initialization
The algorithm starts by creating a two-element list dp. The first element represents the maximum wealth when the trader does not own a stock; it is initialized to zero because no profit has been made yet. The second element represents the maximum wealth when the trader does own a stock; it is seeded with a very large negative number to ensure that any legitimate purchase will replace it.
dp = [0, -99999999] # dp[0]: no stock, dp[1]: holding a stock
Iterative State Transition
For each price p in the input list, a temporary list next is built. The first entry of next captures the best wealth achievable after the day if the trader ends without a stock. This can happen either by staying in the previous “no-stock” state or by selling a held stock at price p. The second entry captures the best wealth after the day if the trader ends holding a stock, which can be achieved either by staying in the previous “holding” state or by buying a new stock at price p and paying the transaction fee.
for p in prices:
next = [0, 0]
next[0] = max(dp[0], dp[1] + p) # sell or stay out
next[1] = max(dp[1], dp[0] - p - fee) # buy or stay in
dp = next
Result Extraction
After processing all prices, the algorithm returns the wealth associated with the “no-stock” state, which by construction is the maximum profit achievable without any leftover holdings.
return dp[0]
Edge Cases Handled
When the price list is empty, the loop body never executes, leaving dp unchanged. The returned value is 0, correctly indicating that no profit can be made without any trading opportunities.
If the list contains a single price, the algorithm evaluates the possibility of buying and immediately selling on the same day. The fee prevents a profitable transaction in this scenario, and the final wealth remains 0.
When the transaction fee exceeds any potential price spread, the max operations ensure that buying is never chosen because the alternative “stay out” state yields a higher wealth. Consequently, the algorithm gracefully avoids unprofitable trades.
The use of a very negative sentinel for the “holding” state guarantees that the first legitimate purchase will replace the sentinel, even if the price is low or the fee is high. This prevents the sentinel from contaminating later calculations.
Performance Optimizations
The implementation achieves constant auxiliary space by reusing two two-element lists (dp and next). No additional data structures proportional to the input size are allocated, which keeps memory usage minimal.
Each iteration performs only a handful of arithmetic and comparison operations. By directly updating the dp reference to the newly computed next list, the code avoids unnecessary copying of larger containers.
The algorithm processes the price array in a single pass, ensuring that the total number of operations grows linearly with the number of days. This tight loop structure benefits from CPU cache locality, as the price values and the two state variables are accessed sequentially.
Integer arithmetic is used throughout, eliminating the overhead of floating-point calculations. The fee is incorporated directly into the purchase transition, avoiding a separate subtraction step later.
Overall, the design balances clarity with efficiency, delivering an optimal solution for the problem constraints.
ELI5 - Simplified Explanation
Imagine you are visiting a magical store that sells sparkly toys. Each day, the price of the toy changes, and you have a special plan to make as much pocket money as possible.
The code keeps track of two pockets. The first pocket holds the money you have when you do not own a toy, and the second pocket holds the money you have while you are busy holding onto a toy.
When a new day starts, the code looks at the price of the toy and decides what to do. One choice is to keep things exactly how they are. Another choice is to sell the toy you already have or buy a new toy for your collection. Because there is a small fee for selling toys, the code subtracts that amount whenever you make a trade.
By checking every single day, the code figures out the best way to move your money back and forth between owning a toy and having cold hard cash. At the end of the journey, you are left with the biggest pile of coins imaginable.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
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++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Go | TS | ||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| FelixFan1122 | C# | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| wisdompeak | Python | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| FelixFan1122 | C# | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| wisdompeak | Python | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 122: Best Time to Buy and Sell Stock II
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 740: Delete and Earn
- problem 931: Minimum Falling Path Sum
- problem 2483: Minimum Penalty for a Shop
- problem 188: Best Time to Buy and Sell Stock IV
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