Vending Machine Coin Mixes

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

An old vending machine in a train station takes only a few kinds of coins and gives no change, so you must pay the exact price. A drink costs 30 cents and the machine accepts 5, 10 and 25 cent coins. You could pay with six 5s, or three 10s, or a 25 and a 5, and so on.

The order you drop coins in does not matter: a 25 then a 5 is the same handful as a 5 then a 25. How many different handfuls of coins pay exactly the price?

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, the number of handfuls itself can be in the trillions, and the recursion visits every one of them.

The same question, like "how many ways to pay 40 cents with only 5s and 10s", comes up again and again inside that recursion. A table answers each such question 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