Skip to content
CodeItRaw
Greedy & Intervals

Lesson 1/4

The greedy method picks what looks best right now at every step and never looks back. It is fast and easy to write. The hard part is seeing that the choice really does no harm: in some problems the local best leads to the overall best, in others it does not.

fives = tens = 0
for bill in bills:
if bill == 5:
fives += 1
elif bill == 10:
fives -= 1
tens += 1
elif tens > 0:
tens -= 1
fives -= 1
else:
fives -= 3
if fives < 0:
return False
return True
Giving change for an item that costs 5: when a 20 comes, spend the 10 first, because 5s are good for everything and a 10 only for changing a 20. Keep what is precious, spend what is not: that is the reason the choice does no harm.

Before writing a greedy solution, try to break it: look for a small input on which the choice turns out badly, and if you cannot find one it is probably right. For coins such an input exists: with coins 1, 3 and 4 the rule "take the largest coin" makes 6 with three coins, and two is right.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Lemonade Stand

    Function

  2. 02

    Fewest Coins

    Code reading · Review the AI

  3. 03

    Fewest Coins

    Code reading · Break the Code

If you would rather not wait for the order, every problem is open without locks: Problem list