Greedy Algorithms8 sections · 316 units
Open in Course

Stock - The Idea

Track the minimum

The greedy insight: at each day, you know the minimum price seen so far. The best profit if you sell today is today's price minus that minimum.

You do not need to check all pairs.

You only need to track one value: the minimum price up to now. As you scan, update the minimum and check if selling today beats your best profit so far.

This is O(n)O(n) time with O(1)O(1) space. A single pass through the array. Common bug: updating min price after computing profit, which allows same-day buy and sell.