Here's my O(n) simple Python solution


  • 0
    G
    class Solution(object):
        def maxProfit(self, prices):
            
            if len(prices) == 0:
                return 0
            
            max_profit = 0
            buyingPrice = prices[0]
            
            for i in xrange(1,len(prices)):
                sellingPrice = prices[i]
                if buyingPrice > sellingPrice:
                    buyingPrice = sellingPrice
                    if (i+1)<=len(prices)-1:
                        i+=1
                        sellingPrice = prices[i]
                max_profit = max(max_profit,sellingPrice-buyingPrice)
            return max_profit
    

Log in to reply
 

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