Here is the solution:
function maxProfit(prices)
if prices is empty then
return 0
minPrice := prices[0]
maxProfit := 0
for i from 1 to length - 1
if prices[i] < minPrice then
minPrice := prices[i]
else
profit := prices[i] - minPrice
maxProfit := max(maxProfit, profit)
return maxProfit
Time: . Space: .
Each day, you either find a new minimum (update minPrice) or check if selling today is profitable (update maxProfit). One pass, two variables.