Maximize profit by finding the best day to buy and sell
The brute force checks all n(n-1)/2 pairs (i, j) where i < j. The optimization: for any sell day j, the optimal buy day is argmin(prices[0..j-1]). Since this minimum only depends on previous elements, we track it incrementally—avoiding repeated scans.
This is equivalent to finding the maximum difference between a peak and its preceding valley in a sequence—a classic prefix minimum pattern.
minPrice: tracks minimum seen so farmaxProfit: tracks best profit foundWe only need the running minimum, not the full prefix minimum array. This "online" property means we can process prices as a stream, discarding each value after extracting its information.
The problem has the "prefix property": the answer at position j depends only on prices[0..j], enabling single-pass processing with constant memory.