All episodes · From a List to Your Map App · Episode 15

Take the Best Step Now: Greedy Algorithms

Pressing play loads the video from YouTube.

A greedy algorithm always takes whatever looks best right now and never looks back. Sometimes that's perfect, and sometimes it's quietly wrong.
We make change with the fewest coins, fit the most meetings into one room (picking the one that starts first fits four, picking the one that ends first fits five, the most possible), watch greedy fail when the coins are one, three and four, and find the rule for when greedy can be trusted.

Every animation in this video is drawn by code, and the narration is an AI voice.

Transcript

To make eighty-six with the fewest coins, grab the biggest coin that fits, again and again. Fifty, twenty, ten, five, one. Always taking whatever looks best right now is called a greedy algorithm. Sometimes it's perfect, and sometimes it's quietly wrong. Today: when greedy works.

With coins of one, five, ten, twenty and fifty, greedy always uses the fewest coins. Five coins for eighty-six. And it never looks back: once a coin is down, it stays down.

Now one room and nine meetings that overlap. How many can you fit without any clash? Greedy idea one: always take the meeting that starts earliest. That fits only four. A better rule: always take the meeting that ends earliest, so the room frees up as soon as possible. That fits five, the most possible.

But change the coins to one, three and four, and make six. Greedy grabs four, then one, then one. Three coins. Yet three plus three needs only two. Grabbing the four looked best, but it blocked the better answer later.

So greedy works when the best choice now never blocks a good choice later. With meetings, ending early only leaves more room for the rest. When that isn't true, you need to try every option without repeating work. That's dynamic programming, in episode twenty-two.

Greedy is fast and simple: one look, one choice, no going back. Just make sure today's best choice can't hurt tomorrow. Next time, a greedy idea that works beautifully: give the most common letters the shortest codes. Huffman coding. See you there.

Next episode: Huffman coding, a greedy idea that works beautifully.

Buy the Developer a Coffee

Entirely up to you: it works the same either way.

Every cup turns into the next update.

WeChat Pay QR code
WeChat Pay
Alipay QR code
Alipay
PayPal QR code
PayPal