All lessons

Greedy Algorithms

7 min · Python examples

Make the locally best choice at each step when that strategy is safe.

Techniques · Greedy Algorithms0/5 cleared

Enemy 1 of 5

This code makes change for 41 by always taking the biggest coin that still fits, then counts the coins used. Press Run to see the total, which is 4.

Why this works

Greedy algorithms pick the best-looking option right now without backtracking. They work when a local optimum leads to a global optimum, like giving the largest coin first in change-making with standard denominations.

You
Bug Slime
Loading editor…
Target output: 4