Best Time to Buy and Sell Stock with Transaction Fee

Problem Id: 714 Difficulty: Medium


Intuition

Solution


class Solution:
    def maxProfit(self, prices: List[int], fee: int) -> int:
        if len(prices) <= 1:
            return 0
        with_stock = -fee
        without_stock = 0
        for i in range(1, len(prices)):
            with_stock, without_stock = (
                max(
                    without_stock - fee,
                    with_stock + prices[i] - prices[i - 1]
                ),
                max(
                    with_stock + prices[i] - prices[i - 1],
                    without_stock
                )
            )
        return without_stock