Leetcode 121: Best Time to Buy and Sell Stock

Iteratively updating minimums and maximum profits in a single pass

The original problem is here.

Problem Solving Approaches

1. Brute Force ($O(N^2)$)

2. Two-pass Approach ($O(2N)$)

3. One-pass Optimal Approach ($O(N)$)

My solution

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_price = float('inf')
        max_profit = 0
        
        for price in prices:
            # Update minimum price
            if price < min_price:
                min_price = price
            # Update maximum profit
            else:
                max_profit = max(max_profit, price - min_price)
                
        return max_profit

Complexity Analysis

Checklist