Sweep left to right; each day either lowers the minimum or tries to improve the best profit.
Carry min_price (cheapest day so far) and best (largest profit so far). On each day, if the price is a new low, it's a better place to buy — remember it. Otherwise, see what selling today at the recorded minimum would earn and keep the max.
A day can't be both a new minimum and a profitable sell (selling at the minimum yields ≤ 0), which is why the two branches are an if / elif.
Algorithm
min_price = +∞,best = 0.- For each price
p: ifp < min_price, setmin_price = p. - Else if
p − min_price > best, setbest = p − min_price. - Return
best.
- Time
- O(n)
- Space
- O(1)
class Solution: def maxProfit(self, prices: list[int]) -> int: min_price = float("inf") best = 0 for p in prices: if p < min_price: min_price = p elif p - min_price > best: best = p - min_price return best