Easy-to-understand Python solution, beats 92%


  • 1
    D
    class Solution(object):
        def maxProfit(self, prices):
            """
            :type prices: List[int]
            :rtype: int
            """
            max_so_far = 0
            if len(prices) < 2:
                return max_so_far
            last_buy_price = prices[0]
            yesterday = prices[0]
            for i in xrange(1, len(prices)):
                today = prices[i]
                if today < yesterday:
                    max_so_far += yesterday - last_buy_price
                    last_buy_price = today
                yesterday = today
            # last chance to sell    
            if today >= prices[-2]:
                max_so_far += today - last_buy_price
            return max_so_far

Log in to reply
 

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