Problem 714

Abstract / Summary

Find the maximum profit from buying and selling stock multiple times while subtracting a fee each time you sell.

Note

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

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]
11 lines | 366 bytes | submitted August 29, 2023 | GitHub   11% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 72% (800k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
  • Greedy
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 “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.

written by openai gpt

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.

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 = 7 | μ = 7.26 | σ = 0.75

Complexity Analysis

Time: linear
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
generated automatically

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++ 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++
38 links | 24 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

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