← All Exercises

Coin Change with Fewest Coins

intermediatego~25min

Background

Coin change is the canonical unbounded knapsack DP: each amount depends on smaller solved amounts, and a sentinel marks unreachable states.

Problem

Given positive coin denominations and a non-negative amount, return the minimum number of coins that sum exactly to amount, or -1 if impossible. Coins may be reused any number of times.

Input

A list of positive coin denominations and a non-negative target amount.

Output

The minimum coin count, or -1 when the amount cannot be formed.

Sample tests

Sample 1

Input: coins = [1, 2, 5], amount = 11
Expected: 3

Sample 2

Input: coins = [2], amount = 3
Expected: -1

Sample 3

Input: coins = [2, 5], amount = 0
Expected: 0

Your solution

Learning objective

Formulate an unbounded knapsack DP with a sentinel and iterate amounts in increasing order.