1. Track the Cheapest Day So Far Optimal
Intuition
The day to buy is always the cheapest day before the sale. Selling on day i earns today's price minus the cheapest day before it — so only one number from the past matters. Carry the minimum seen so far, and every day answers in constant time. That reframing, from "which pair" to "what do I need from the past", is the whole lesson.
Algorithm
1. Track the lowest price seen so far and the best profit so far.
2. On a day whose price is higher than that lowest price, the profit is today's price minus that lowest price.
3. Keep the better profit; on any other day, today's price becomes the lowest price instead.
4. Never-profitable inputs leave the profit at zero, which is the right answer.
Time & Space
Time O(n) — one pass. Space O(1).