Problem 183
Coin Change
Medium · 20 pts · Array, Dynamic Programming, Breadth-First Search
Problem
You are given N coin denominations, with an unlimited supply of each, and an amount S. Find the fewest coins whose values add up to exactly S, or print -1 if S cannot be made. An amount of 0 needs 0 coins. Greedily taking the largest coin does not always work (with coins 1, 3, 4 the amount 6 is best as 3 + 3, not 4 + 1 + 1). Use dynamic programming: min[x] = 1 + the smallest min[x - coin] over all coins that fit, for x from 1 to S.
Input
First line: integers N (number of denominations) and S. Second line: N coin values.
Output
Print the minimum number of coins, or -1.
Constraints
1 <= N <= 12; 1 <= coin <= 2147483647; 0 <= S <= 10000
Example input
3 11 1 2 5
Example output
3
Explanation
With coins 1, 2 and 5, the amount 11 can be made as 5 + 5 + 1, using 3 coins. No combination of 2 coins reaches 11 (the most is 5 + 5 = 10), so the answer is 3.