714. Best Time to Buy and Sell Stock with Transaction Fee
Problem
prices[i] is a stock's price on day i. Make as many transactions as you like (holding at most one share at a time), paying fee for each one. Return the maximum profit.
Example: prices = [1,3,2,8,4,9], fee = 2 → 8 (buy 1, sell 8; buy 4, sell 9)
Constraints: n ≤ 5·10⁴.
Two states: hold and cash. cash = max(cash, hold + p − fee), hold = max(hold, cash − p).
Complexity: O(n) time, O(1) space.
class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
cash, hold = 0, -prices[0]
for p in prices[1:]:
cash = max(cash, hold + p - fee)
hold = max(hold, cash - p)
return cash
assert Solution().maxProfit([1, 3, 2, 8, 4, 9], 2) == 8
assert Solution().maxProfit([1, 3, 7, 5, 10, 3], 3) == 6
class Solution {
public int maxProfit(int[] prices, int fee) {
int cash = 0, hold = -prices[0];
for (int i = 1; i < prices.length; i++) {
cash = Math.max(cash, hold + prices[i] - fee);
hold = Math.max(hold, cash - prices[i]);
}
return cash;
}
}
func maxProfit(prices []int, fee int) int {
cash, hold := 0, -prices[0] // best profit without / with a share in hand
for _, p := range prices[1:] {
cash = max(cash, hold+p-fee)
hold = max(hold, cash-p)
}
return cash
}