Skip to content
BytePatterns

Fewest Coins for an Amount

MediumDynamic Programming#bottom-up-dp#unbounded-knapsack~30m

Problem

A machine pays out change using coin values from a given list, and it has an unlimited supply of every value. Return the smallest number of coins that add up to exactly amount, or -1 if no combination of coins reaches it. Coin values are positive and distinct, and an amount of 0 needs no coins at all.

Examples

Input:  coins = [1, 4, 6], amount = 8
Output: 2
Why:    4 + 4; grabbing the 6 first leads to 6 + 1 + 1, three coins
Input:  coins = [5, 10], amount = 3
Output: -1
Why:    every coin is bigger than the amount
Input:  coins = [2], amount = 0
Output: 0
Why:    edge case, nothing to pay

Hints

0 / 3

Stuck on the idea rather than the code? Coin Change covers it.