Given coin denominations and a target amount, return the fewest coins that make the amount, or -1 if it is impossible. You have an unlimited supply of each coin.
Input
- Line 1: n, the number of denominations (
1 ≤ n ≤ 12)
- Line 2: n distinct positive integers
- Line 3: the amount (
0 ≤ amount ≤ 10^4)
Output
The minimum number of coins, or -1.
Why interviewers like it
Greedy (always take the biggest coin) is wrong: with coins 1 3 4 and amount 6, greedy gives 4+1+1 = 3 coins but the answer is 3+3 = 2. Spotting that is the point.
Read from standard input and write to standard output. 5 test cases in total (3 hidden). Tests for this language run inside your browser.