CodeBlanks Logo Icon CodeBlanks

Challenge 4

Print the greedy coin change solution.

Challenge 4: Greedy

In this challenge you will print the greedy coin change solution.

Coins: [25, 10, 5, 1]. Amount: 63. Output: 6.

Greedy takes the largest coin each step; it is optimal on standard systems.

Practice Greedy coin count

Write greedy_coins(coins, amount). Print the minimum coin count with greedy. Output: 6.

Starter code

solution.py
def greedy_coins(coins, amount):
    # Greedy coin count

Sample solution

solution.py
def greedy_coins(coins, amount):
    # Greedy coin count
    coins.sort(reverse=True)
    count = 0
    for coin in coins:
        count += amount // coin
        amount = amount % coin
    print(count)
greedy_coins([25, 10, 5, 1], 63)

Expected output

6

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How many coins does greedy give for 63 with [25,10,5,1]?

  • 5
  • 6 Correct answer
  • 4
  • 7

Explanation: 6.

2 Challenge 4: match the terms

Term Meaning
greedy Local best
coin Coin
amount Amount
sort Sort

All lessons in Intermediate