Notes

Personal notes on various topics

View on GitHub

Intuition

Instead of checking every possible pair of days, we can keep track of the minimum price seen so far as we iterate through the list. For each day, we calculate the profit if we sold on that day (current price minus the minimum price so far) and update the maximum profit accordingly. This way, we only need a single pass through the array.

Approach

Complexity

Code

from typing import List

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        max_profit = 0
        buy_price = prices[0]

        for i in range(1, len(prices)):
            max_profit = max(max_profit, prices[i] - buy_price)
            buy_price = min(buy_price, prices[i])
        
        return max_profit

Back to Problem Statement