Easy understand Python solution


  • 0
    H

    The idea is to use a boolean to check whether we hold a stock that is available to sell. We just go backwards to keep track of the current max price and current min price. Once the current min price is the local minimum we sell the stock.

    def maxProfit(self, prices):
        curmaxprice, curminprice, res = 0, 9999, 0
        hold = False
        for i in xrange(len(prices) - 1, -1, -1):
            if i != 0:
                if prices[i] > prices[i-1]:
                    curmaxprice = max(curmaxprice, prices[i])
                    curminprice = min(curminprice, prices[i-1])
                    hold = True
                else:
                    if hold:
                        res += curmaxprice - curminprice 
                        hold = False
                        curmaxprice = prices[i - 1]
                        curminprice = 9999
            else:
                if hold:
                        res += curmaxprice - curminprice 
                        hold = False
                        curmaxprice = prices[i - 1]
                        curminprice = 9999
        return res

Log in to reply
 

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