← All Exercises

Minimum Coins for an Amount

intermediatejavascript~25min

Background

Coin change is the canonical unbounded knapsack problem and models making change, resource allocation, and minimum-step problems.

Problem

Given coin denominations and a target amount, return the minimum number of coins that sum exactly to the amount, or -1 if it cannot be formed.

Input

An array of positive integer coin values and a non-negative integer amount.

Output

The minimum coin count, 0 for amount 0, or -1 when no combination exists.

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 = [1], amount = 0
Expected: 0

Your solution

Learning objective

Build a one-dimensional DP over amounts and handle unreachable states with a sentinel value.