Easy to understand Python with explanation


  • 0
    R

    whenever price is going up, record start price and at the end of going up, use local maximum to subtract start and collect it, whenever we going down, just increase i and do nothing.

    class Solution(object):
        def maxProfit(self, prices):
            """
            :type prices: List[int]
            :rtype: int
            """
            start=0
            i=0
            c=0
            while i<=len(prices)-2:
                start=i
                while i<=len(prices)-2 and prices[i]<=prices[i+1]:
                    i+=1
                c+=prices[i]-prices[start]
                while i<=len(prices)-2 and prices[i]>prices[i+1]:
                    i+=1
            return c
    

Log in to reply
 

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