← Sliding Window
Problem
You're given a sequence of daily stock prices. You may buy on one day and sell on a later day, at most once. Find the maximum profit achievable — or 0 if no profitable trade exists.
Signal
Whenever the best answer is "a later value minus the best earlier extreme seen so far," that's a single forward pass with a running best — not a window that grows and shrinks from both ends. One pointer, two scalars.
Approach
Scan left to right, keeping the lowest price seen so far. At each day, the best profit if you sold today is today's price minus that running minimum. Track the best profit across all days as you go. No lookback, no window — just one pass.
Skeleton
min_price = infinity
best = 0
for price in prices:
min_price = min(min_price, price)
best = max(best, price - min_price)
Solution
def max_profit(prices: list[int]) -> int:
min_price = float("inf")
best = 0
for price in prices:
min_price = min(min_price, price)
best = max(best, price - min_price)
return best
Complexity
O(n) time — one pass. O(1) space — two running scalars, no auxiliary structure.
Pitfalls
- Confusing this with Kadane's max-subarray — both are one-pass running-best problems, but here you track a running minimum price, not a running sum.
- There's nothing to slide here. Resist bolting on a two-pointer window template; a single forward pointer is the whole solution.
- The "no profit possible" case (strictly decreasing prices) falls out for free
since
beststarts at 0 — worth testing explicitly rather than assuming.