Python Simple O(N) Solution, keep track of minimum price before


  • 0
    J

    At price p, calculate profit based on the minimum price previously seen.
    Then update the min_price.

    class Solution(object):
        def maxProfit(self, prices):
            """
            :type prices: List[int]
            :rtype: int
            """
            max_profit = 0
            min_price = None
            
            for p in prices:
                if min_price == None:
                    min_price = p
                else:
                    max_profit = max(p-min_price, max_profit)
                    min_price = min(min_price, p)
            return max_profit
    

Log in to reply
 

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