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
fewestwithfewest[0]= 0 and the rest infinite. For each amount from 1 to the requested one, try every coinmthat fits and keep the minimum offewest[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: dandGreedy algorithm: g, with the number of coins orImpossible.
1 3 4
6
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