def max_profit(prices):
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
Variables
n- length of the prices array
Explanation
A single pass tracking the running minimum and the best gap so far - **O(n)** time, **O(1)** space. The brute-force "all pairs" version is O(n²); recognizing that you only need the min-so-far on the left is the trick.