Best Time to Buy and Sell Stock

Key Idea

Solution

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # Understanding:
            # Iterate and find maximal difference
            # Array is irregular
            # You can only go forward, meaning you have to finding earnings forward
            # Read the question carefully you do NOT need to report the index, only MAXIMIZED earning
        # Track lowest prices so far
        lowest = prices[0]
        # Earnings
        earnings = 0

        # Iterate
        for price in prices:
            # If the current price beats the lowest you saw
            if price < lowest:
                # Update the lowest price
                lowest = price
            # If current price does NOT beat
            else:
                # find the maximum earnings comparing to previous earnings
                earnings = max(earnings, price - lowest)
        return earnings

Complexity