class Solution(object): def maxProfit(self, prices, fee): state = profit = 0 last_price = prices for price in prices[1:]: state += price - last_price if state > fee: profit += state - fee state = fee else: if state < 0: state = 0 last_price = price return profit
. state is a switch variable
. when state >= fee, all incoming positive price movement will become profit
. when state <= 0, that, all incoming negative price movement will be discarded
[python] best run : 149 ms, beats 98.92% at this time, 35%+ faster than the "max" solution.
[java] best run: 13ms, beats 97.42% at this time, 20%+ faster than the "max"