Labs ICT
โญ Pro Login

Greedy Algorithms

Make the locally optimal choice at each step.

Greedy algorithms are the "take the best option right now" approach. At each step, you pick the choice that looks best without worrying about future consequences. No looking back, no reconsidering.

Think of it like eating at a buffet โ€” you grab whatever looks tastiest on your current pass. You do not save room for something better later. Sometimes that works out great. Sometimes you fill up on bread and miss the steak.

The Greedy Choice Property

For a greedy algorithm to work, the problem must have the greedy choice property. This means making the locally optimal choice at each step leads to a globally optimal solution. It is not enough to pick what looks best right now โ€” that choice has to actually be part of the best overall solution.

The coin change problem with standard denominations is a good example. To make 37 cents, you grab the largest coin that fits (25), then the next largest (10), then two pennies. Greedy works perfectly here because of how coins are designed.

When Greedy Works and When It Does Not

Greedy shines in problems like activity selection, Huffman coding, and minimum spanning trees. These have the right structure where local optima line up with the global optimum.

But for many problems, greedy fails spectacularly. The classic coin change example with weird denominations (say, 1, 3, 4 cents) breaks greedy โ€” to make 6 cents, greedy picks 4+1+1 (three coins) when the optimal is 3+3 (two coins). When greedy fails, you need Dynamic Programming instead.

Greedy vs Dynamic Programming

Both solve optimization problems, but their strategies differ. DP considers all options and picks the best combination. Greedy picks the best single option and commits. DP is like checking every route on a map. Greedy is like following the GPS that always turns toward what looks closest.

Greedy algorithms are usually simpler and faster โ€” O(n log n) or better. Use them when the problem structure supports it. When you are not sure, try greedy first. If it fails on a small example, switch to DP. That is the practical workflow most developers follow.

๐Ÿงช Quick Quiz

What is a greedy algorithm?