Payments app~25 min2s · 256 MBtarget O(amount × n) time, O(amount) spaceclassic twin: lc-518knapsack
A payments app lets a customer cash out an exact amount at a kiosk. The kiosk holds notes of a few fixed values, and it has as many notes of each value as it needs.
Support wants to know how many different combinations of notes pay the amount. Two combinations are the same when they use the same number of notes of each value. The order in which notes come out does not matter.
Write ways_to_make_change(amount, coins).
amount is the amount to pay, a whole number of units.coins lists the note values. Each value appears once, and each can be used any number of times.amount, modulo 1,000,000,007.Input: amount = 5, coins = [1, 2, 3]
Output: 5Let ways[a] be the number of combinations of the notes read so far that pay a. Start with ways[0] = 1, because paying nothing is one combination. Read the notes one at a time. For each note, go through the amounts upwards from its value and add ways[a - note] to ways[a].
| after | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| (none) | 1 | 0 | 0 | 0 | 0 | 0 |
| coin 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| coin 2 | 1 | 1 | 2 | 2 | 3 | 3 |
| coin 3 | 1 | 1 | 2 | 3 | 4 | 5 |
The last cell holds 5. The combinations are 3+2, 3+1+1, 2+2+1, 2+1+1+1 and 1+1+1+1+1.
Input: amount = 3, coins = [2]
Output: 0Notes of 2 never add up to an odd amount.
Input: amount = 3, coins = [1, 2]
Output: 2The combinations are 1+1+1 and 1+2. The order 2+1 is the same combination as 1+2.
1 ≤ amount ≤ 50001 ≤ len(coins) ≤ 100, and every value is between 1 and 5000, all differentThere are up to 100 note values and 5,000 amounts, so a table with one entry for each pair has 500,000 entries. Counting combinations one by one cannot work, because the number of combinations is far larger than any machine can list. Work per amount and per note, about half a million small steps.