Intuitive Python O(n) solution using start and end pointers


  • 3
    B
    class Solution:
    # @param prices, a list of integer
    # @return an integer
    def maxProfit(self, prices):
        length=len(prices)
        if length==0:
            return 0
            
        maxprofit=0
        start=0
        end=0
        
        for i in range(1,length):
            if prices[i]<prices[start]:
                start=i
                end=i
            elif prices[i]>prices[end]:
                end=i
                maxprofit=max(maxprofit,prices[end]-prices[start])
                
        return maxprofit
    

    In general this compares all (potentially) larger profits and find the maximum of them to return the optimum


  • 0
    B
    This post is deleted!

  • 0
    S

    Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example


Log in to reply
 

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