Complexity and efficiency · 15 / 15 Exercise Hard

Coin change

Objective

Create a Python program that computes the fewest coins needed to pay an amount with dynamic programming, and compares it with the greedy algorithm (always take the largest coin possible), which is sometimes not optimal.

Instructions

  • Read a line with the coin values (distinct positive integers, with unlimited supply of each) and then a line with the amount to pay (integer ≥ 0).
  • Dynamic programming: create a list fewest with fewest[0] = 0 and the rest infinite. For each amount from 1 to the requested one, try every coin m that fits and keep the minimum of fewest[amount - m] + 1.
  • Greedy: sort the coins from largest to smallest and from each one take all the coins that fit using // and %. If something is left over at the end, there is no solution.
  • Show Dynamic programming: d and Greedy algorithm: g, with the number of coins or Impossible.
Input
1 3 4
6
Output
Dynamic programming: 2
Greedy algorithm: 3

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise