Simple Python 42ms Solution

  • 1
    Disclaimer - This solution is probably one of the most common solutions, I have no clue as I haven't looked into the discussions here for this particular question. Therefore, there might be other similar/same solutions available in python. Some of them might even be better, but I hope this is helpful. :)

    class Solution(object):
    def maxProfit(self, prices):
    :type prices: List[int]
    :rtype: int

        if len(prices) <= 1:
            return 0
        min_so_far = prices[0]
        max_profit = 0
        for elem in prices[1:]:
            max_profit = max(max_profit, elem - min_so_far) # max profit from min_so_far in list
            min_so_far = min(min_so_far, elem)
        return max_profit

Log in to reply

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