Best Time Buy/Sell Stock With Fee — State DP
Advertisement
Problem
Unlimited transactions, but each sell has a transaction fee. Maximize profit.
Solutions
Python
class Solution:
def maxProfit(self, prices: list[int], fee: int) -> int:
cash,hold=0,-prices[0]
for p in prices[1:]:
cash,hold=max(cash,hold+p-fee),max(hold,cash-p)
return cash
C++
class Solution {
public:
int maxProfit(vector<int>& p, int fee){
int cash=0,hold=-p[0];
for(int i=1;i<p.size();i++){
cash=max(cash,hold+p[i]-fee);
hold=max(hold,cash-p[i]);
}
return cash;
}
};
Complexity
- Time: O(n) | Space: O(1)
Advertisement