Greedy Algorithms — ELI5

Imagine you are at a buffet. Your plate has limited space. The greedy strategy is: always grab the most delicious-looking dish next. You do not plan your whole plate in advance — you just pick the best thing available right now.

That is a greedy algorithm. At every step, you make the choice that looks best right now, without worrying about what comes later. You never go back and change your mind.

Here is a real example. You have coins worth 25¢, 10¢, 5¢, and 1¢. Someone asks you to make 36¢ using the fewest coins possible. The greedy approach: always pick the largest coin that fits.

  • 36¢: grab a 25¢ coin. Left: 11¢
  • 11¢: grab a 10¢ coin. Left: 1¢
  • 1¢: grab a 1¢ coin. Done!

Three coins total: 25 + 10 + 1. That is actually the best answer — you cannot do better.

The amazing thing about greedy algorithms is how simple they are. No fancy planning. No exploring every possibility. Just grab the best option each time. And for many problems, this actually gives the perfect answer.

But here is the catch: greedy does not always work. Imagine coins worth 25¢, 15¢, and 1¢, and you need 30¢. Greedy says: grab 25¢, then five 1¢ coins — six coins total. But two 15¢ coins would be only two coins. Greedy got tricked because grabbing the biggest first blocked the better path.

So greedy algorithms are like a shortcut. When the shortcut works, it is fast and elegant. But you have to be careful — sometimes the shortcut leads you astray.

One thing to remember: A greedy algorithm always picks the best-looking option right now. It works beautifully for some problems and fails completely for others. The skill is knowing which is which.

pythonalgorithmsgreedy

See Also