121. Best Time to Buy and Sell Stock

Description

See https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

Solution

Pretty straight forward problem and solution. Iterate through the array looking for a lower price than the current one (which is initialized to the first element in the list). Profit is the difference between the current item and the lowest price. Keep track of the max profit.

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        low_price = prices[0]
        profit = 0
        # start at 1 since element 0 is used to initialize the low_price
        for i in range(1, len(prices)):
            if prices[i] <= low_price:
                low_price = prices[i]
            else:
                profit = max(profit, prices[i] - low_price)
        return profit

Space O(1), Time O(N)

Last updated