Goal
Given an array of prices, compute the maximum possible profit from a single buy → sell transaction.
Key Idea (Intuition)
You must buy before you sell. For any day treated as the sell day, the best buy is simply the
lowest price seen so far. So we maintain two running values while scanning once:
minPrice (lowest price up to the current day) and maxProfit (best profit found so far).
At each day, we (1) compute today’s possible profit against minPrice and update maxProfit,
then (2) update minPrice with today’s price.
Initialization
maxProfit = 0— best profit found so far.minPrice = Infinity— the minimum price seen so far; first price will become the initial minimum.
Traversal
Iterate over the array prices from left to right (one pass). For each price:
Per-Iteration Logic
-
Compute possible profit at this sell point:
possibleProfit = price − minPrice
Treat today as the sell day; compare with the lowest buy price seen so far. -
Update maxProfit:
maxProfit = Math.max(maxProfit, possibleProfit)
Keep the best profit encountered so far. -
Update minPrice:
minPrice = Math.min(minPrice, price)
Refresh the lowest-so-far price for future sell-day checks.
Return
After the loop finishes, return maxProfit.
Why This Works
A single pass is enough because for each day we only need the minimum price from previous days.
By maintaining minPrice, we can directly calculate the best possible profit if we sell at today’s price.
By maintaining maxProfit alongside, we always keep track of the best profit across all days.