Share my O(n) Time and O(1) space python solution With Comments


  • 1
    S
       def maxProfit(self, prices):
           """
           :type prices: List[int]
           :rtype: int
           """
           prevmax=float('-inf')
           prevmin=float('inf')
           maxprofit=0
           for i in range(0,len(prices)):
               if prices[i]<prevmin:#if A[i] less than previously found minimum we will update both max and min tiil now to A[i]
                   prevmin=prices[i]
                   prevmax=prices[i]
               elif prevmax<prices[i]:# if A[i] is greater than prevmax we will update prevmax
                   prevmax=prices[i]
               maxprofit=max(maxprofit,prevmax-prevmin)    
           return maxprofit

Log in to reply
 

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