714. Best Time to Buy and Sell Stock with Transaction Fee
# O(n) time || O(1) space
def max_profit(self, prices: List[int], fee: int) -> int:
res, hold = 0, -prices[0]
for price in prices[1:]:
res = max(res, hold + price - fee)
hold = max(hold, res - price)
return res
A dynamic programming approach can be efficient here. The idea is to keep track of two variables at each step:
Cash: The maximum profit we can have if we don’t hold a stock at the end of day i.Hold: The maximum profit we can have if we do hold a stock at the end of day i.
Here’s the step-by-step approach:
-
Initialize Variables:
cashis initially 0 since we start without any stock.holdis initially-prices[0]since buying a stock would cost usprices[0].
-
Iterate Through the Array:
- For each day’s price, calculate the new
cashandholdvalues:new_cashis the maximum of the previouscashand the profit from selling the stock today(hold + price - fee).new_holdis the maximum of the previousholdand the balance after buying the stock today(cash - price).
- Update
cashandholdwith these new values for the next iteration.
- For each day’s price, calculate the new
-
Return
cash:- At the end,
cashwill contain the maximum profit that can be achieved.
- At the end,