Facebook Pixel

Prerequisite: Unbounded Knapsack Introduction

This is an unbounded knapsack problem: each coin denomination can be used unlimited times. We minimize coin count rather than count combinations.

You are given a list coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. Each coin can be used any number of times. If amount cannot be made up by any combination of the coins, return -1.

Input & Output
Input
coins — the available coin denominations, each usable any number of times
amount — the total amount to make up
Output
the fewest coins that add up to amount, or -1 if the amount cannot be made
Example
Input
coins = [1, 2, 5], amount = 11
Output
3
Explanation

11 = 5 + 5 + 1 uses three coins, and no combination reaches 11 with two.

Example
Input
coins = [1, 3, 4], amount = 6
Output
2
Explanation

6 = 3 + 3 uses two coins. Repeatedly taking the largest coin that fits gives 4 + 1 + 1, three coins, so the greedy choice is not always optimal.

Example
Input
coins = [3], amount = 1
Output
-1
Explanation

No multiple of 3 equals 1, so the amount cannot be made at all.

Constraints
  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 2^31 - 1
  • 0 <= amount <= 10^4

Try it yourself

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro