Vending Machine Coin Mixes

Mediumdynamic programmingAlso known as Coin Change II (number of combinations)

An old station vending machine gives no change, so you must pay the exact price. A drink costs 30 cents and the machine takes 5, 10 and 25 cent coins: six 5s, three 10s, a 25 and a 5, and so on.

Order does not matter: a 25 then a 5 is the same handful as a 5 then a 25. You want the number of different handfuls.

Your task

Write countMixes(coins, price). coins lists the accepted coin values, and you have as many of each as you need. Return how many different handfuls add up to exactly price. Two handfuls are the same if they contain the same number of each coin value.

A price of 0 has exactly one handful: no coins at all. If the price cannot be paid, return 0.

countMixes(coins: int[], price: int) → int

Examples

Example 1
Input
coins = [5, 10, 25]
price = 30
Output
5
Why

The handfuls are: six 5s; one 10 and four 5s; two 10s and two 5s; three 10s; one 25 and one 5. That is 5.

Example 2
Input
coins = [2, 3]
price = 7
Output
1
Why

Only 2 + 2 + 3 works. Counting orders would give 3 (2-2-3, 2-3-2, 3-2-2), but those are all the same handful.

Constraints

  • 1 ≤ coins.length ≤ 10
  • 1 ≤ coins[i] ≤ 500, all values different
  • 0 ≤ price ≤ 500
  • The answer is below 10¹⁵.
Start with brute force

Recursively choose how many of each coin to use and count the choices that hit the price. With a 1-cent coin and many coin types, there can be trillions of handfuls, and the recursion visits every one.

The same subquestion, like "how many ways to pay 40 cents with only 5s and 10s", comes up again and again. A table answers each one once.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code