Best Time to Buy and Sell Stock with Transaction Fee
Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #714
Trade as many times as you like, holding at most one share at a time. Each completed transaction (buy + sell) costs fee. Return the maximum profit.
Examples
text
prices = [1,3,2,8,4,9], fee = 2 → 8 (buy 1 sell 8: 5; buy 4 sell 9: 3)
prices = [1,3,7,5,10,3], fee = 3 → 6Hints
- Unlike Stock II, small wiggles aren't worth trading because of the fee.
- At the end of each day you either hold a share or you don't. Write a recurrence for each state.
Approach
State machine DP:
text
cash = 0 # best profit with no share
hold = -prices[0] # best profit while holding a share
for p in prices[1:]:
cash = max(cash, hold + p - fee) # sell today (pay the fee)
hold = max(hold, cash - p) # buy todayUsing the updated cash in the hold line is safe. It amounts to selling and rebuying on the same day, which never helps because of the fee. This two-state template also solves Stock II (fee = 0) and, with a third state, Stock with Cooldown.
Complexity
Time: O(n). Space: O(1).
Python solution
def maxProfit(prices, fee):
cash, hold = 0, -prices[0]
for p in prices[1:]:
cash = max(cash, hold + p - fee)
hold = max(hold, cash - p)
return cashJavaScript solution
function maxProfit(prices, fee) {
let cash = 0, hold = -prices[0];
for (let i = 1; i < prices.length; i++) {
cash = Math.max(cash, hold + prices[i] - fee);
hold = Math.max(hold, cash - prices[i]);
}
return cash;
}