121. Best Time to Buy and Sell Stock

Easy

Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note: that you cannot sell a stock before you buy one.

😇 Solution

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices:
            return 0
        
        min_price = max(prices)
        max_profit = 0
        
        for i in range(len(prices)):
            if prices[i] < min_price:
                min_price = prices[i]
                
            profit = prices[i] - min_price
            if profit > max_profit:
                max_profit = profit
                
        return max_profit

Last updated

Was this helpful?