GRDY-P6

When greedy change fails

Practice 6 of 6Greedy algorithms10 tests

The problem

coins lists the coin values of a country, all different, in any order, and one of them is 1. To pay an amount, the greedy method takes the largest coin that fits, again and again. Return the smallest amount (at least 1) for which the greedy method uses more coins than the fewest possible. If the greedy method is always best, return None.

first_failure([1, 3, 4])   # 6: greedy 4+1+1, best 3+3
first_failure([1, 2, 5, 10, 20, 50, 100, 200, 500])   # None

Lesson 5 gives the fact you need: if greedy ever fails, it fails for some amount below the sum of the two largest coins.

Limits

  • Up to 16 coins, the largest up to 100,000. Aim for O(L × k), where L is the sum of the two largest coins and k the number of coins.

Builds on GRDY-5 When greedy fails.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

10 tests, not run yet
Test results
#TestResultReads · time
1Coins 1, 3, 4Not run
2India's coins and notesNot run
3Coins 1, 10, 25Not run
4Only the 1Not run
5Two coinsNot run
6Coins 1, 5, 12Not run
7Powers of twoNot run
8Not in orderNot run
9A failure far awayNot run
10A large canonical systemNot run