← Problem setPython
#121EasySliding window
Best Time to Buy and Sell Stock
The tell: Best single buy-then-sell pair, where the buy must precede the sell.
How you get there
- 1Track the cheapest price seen so far as you sweep forward.
- 2At each day the best sale today is price − cheapest-so-far.
- 3One pass, no need to consider pairs explicitly.
Solution
def max_profit(prices: list[int]) -> int:
cheapest = float("inf")
best = 0
for price in prices:
cheapest = min(cheapest, price)
best = max(best, price - cheapest)
return best- Time
- O(n)
- Space
- O(1)
What goes wrong
Updating the answer before the minimum allows selling on the same day you buy — harmless here, wrong in variants.