Best Time to Buy and Sell Stock with Transaction Fee
Pattern: Stock buy and sell
Each sale pays a fee. Track hold (the best money while holding a share) and free (while holding none): buy from free, sell from hold and pay the fee.
The problem
Return the most profit from any number of transactions, where each transaction costs fee.
Think first
- Why does summing every rise no longer work?
- What two states describe a day?
- When is the fee paid?
Hints
Brute force, and why it fails
Try every set of transactions: exponential.
The key insight
With two states per day, the fee becomes one extra subtraction on the sell transition.
Dry run
| profit | 5 |
|---|
[1, 3, 2, 8, 4, 9], fee 2. Buy at 1, sell at 8: 8 - 1 - 2 = 5.
Step 1 of 2
The plan
hold = -inf; free = 0
for p: hold = max(hold, free - p); free = max(free, hold + p - fee)
Complexity
- Time
O(n)- Space
O(1)
Two numbers per day.
Edge cases
- Fee larger than every rise: 0.
- Fee 0: as problem II.
- One day.
I've built my logic, show the code
Java
class Solution {
public int maxProfit(int[] prices, int fee) {
long hold = Long.MIN_VALUE / 2, free = 0; // best money while holding a share / while holding none
for (int p : prices) {
long newHold = Math.max(hold, free - p); // keep holding, or buy today
long newFree = Math.max(free, hold + p - fee); // keep waiting, or sell today and pay the fee
hold = newHold;
free = newFree;
}
return (int) free;
}
}C++
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
long long hold = LLONG_MIN / 2, free = 0; // best money while holding a share / while holding none
for (int p : prices) {
long long newHold = max(hold, free - p); // keep holding, or buy today
long long newFree = max(free, hold + p - fee); // keep waiting, or sell today and pay the fee
hold = newHold;
free = newFree;
}
return static_cast<int>(free);
}
};Python
class Solution:
def maxProfit(self, prices: list[int], fee: int) -> int:
hold, free = float("-inf"), 0 # best money while holding a share / while holding none
for p in prices:
hold, free = max(hold, free - p), max(free, hold + p - fee) # buy today / sell today and pay the fee
return freeCommon mistakes
- Paying the fee on both buy and sell.
- Starting hold at 0.