SDE & MLE Prep

121. Best Time to Buy and Sell Stock

Problem

prices[i] is a stock's price on day i. Buy on one day and sell on a later day; return the maximum profit, or 0 if no profit is possible.

Example: [7,1,5,3,6,4] → 5 (buy at 1, sell at 6); [7,6,4,3,1] → 0

Constraints: n ≤ 10⁵.

Track the cheapest price so far; each day, profit = price − min so far.

Complexity: O(n) time, O(1) space.

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        lo, best = float("inf"), 0
        for p in prices:
            lo = min(lo, p)
            best = max(best, p - lo)
        return best