Given daily stock prices, find the maximum profit from buying on one day and selling on a later day (or 0 if no profit is possible).
It's the simplest introduction to tracking a running best-so-far value in a single pass.
Whenever you need "the best result using an earlier value", track that earlier value's running minimum/maximum as you scan instead of comparing every pair.
Track `minPriceSoFar` as you scan the array once. At each day, the best profit achievable by selling today is `price[i] - minPriceSoFar`; keep a running `maxProfit` of that value, then update `minPriceSoFar` if today's price is lower. One pass, constant extra space.
class Solution {
public int maxProfit(int[] prices) {
int minPriceSoFar = Integer.MAX_VALUE;
int maxProfit = 0;
for (int price : prices) {
if (price < minPriceSoFar) {
minPriceSoFar = price;
} else if (price - minPriceSoFar > maxProfit) {
maxProfit = price - minPriceSoFar;
}
}
return maxProfit;
}
}