faster than the "max" solution and very clear answer


  • 3
    X
    class Solution(object):
        def maxProfit(self, prices, fee):
            state = profit = 0 
            last_price = prices[0] 
            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
    

    Explanation:
    . 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"


  • 0
    L

    this is brilliant!


  • 0
    Q

    This is awesome!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.