Return the fewest coins for an amount with custom denominations
A vending machine runs in an arcade that issues its own tokens, so the coin values are not the usual 1, 5, 10, 25. The machine must hand back change using as few coins as possible (the coin tube is small), and the display shows exactly which coins are coming out.
Implement makeChange(amount, coins). It returns the coins to dispense, or null if the exact amount cannot be made.
makeChange(amount, coins) // => number[] | null
amount is a non-negative integer, at most 10,000.coins lists the available denominations: positive integers in any order, possibly with duplicates. The machine has an unlimited supply of each.amount, using the fewest coins possible, sorted from largest to smallest.amount is 0, return []. If the amount cannot be made, return null.coins.Always taking the largest coin that fits works for US coins but not in general. With coins [1, 3, 4] and amount 6, greedy gives 4 + 1 + 1 (three coins) while 3 + 3 needs only two.
makeChange(6, [1, 3, 4]); // => [3, 3]
makeChange(30, [25, 10, 1]); // => [10, 10, 10]
makeChange(68, [1, 5, 10, 25]); // => [25, 25, 10, 5, 1, 1, 1]
makeChange(11, [5, 1, 5, 2]); // => [5, 5, 1]
makeChange(7, [1, 2, 3, 4, 5]); // => [5, 2] or [4, 3]
makeChange(7, [2, 4]); // => null
makeChange(0, [3]); // => []
When several answers are possible, tests check that your coins are valid denominations, sorted largest first, add up to amount, and that there are as few of them as possible. Otherwise they compare the exact array.