Share my simple python code using DP method with explaination


  • 0
    Z
    def maxProfit(self, prices):
        length=len(prices)
        if length<2:
            return 0
        maxAll=prices[1]-prices[0]
        maxLast=maxAll
        i=2
        while i<length:
            pro=prices[i]-prices[i-1]
            maxLast=max(pro,pro+maxLast)
            maxAll=max(maxLast,maxAll)
            i=i+1
        if maxAll<0:
            maxAll=0
        return maxAll
    

    This problem is same with the maximum-subarray problem.
    When at the i day, the maxAll is the max profile before i day, and the maxLast is the max profile when we sell the stock at i-1 day. And go through the array and we can get the last result.


Log in to reply
 

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