-
Notifications
You must be signed in to change notification settings - Fork 2
Coin Changing (Unlimited Coin Supply)
Rafiul Islam edited this page Nov 23, 2018
·
3 revisions
-
0 1 2 3 4 5 6 7 8 0 inf inf inf inf inf inf inf inf
for(int money=0; money<=target; money++)
{
for(int i=0; i<len; i++)
{
/// next coin from supply is greater then current coin in table
if(money < coins[i])
break;
/// set minimum value for current coin amount making in table
if(coin_table[money] > coin_table[money-coins[i]]+1)
coin_table[money] = coin_table[money-coins[i]]+1;
}
}coins = {1, 2, 3}
current table:
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| 0 | inf | inf | inf | inf | inf | inf | inf | inf |
1 - coins[0] = 1 - 1 = 0
table[0] = 0
table[1] = inf
table[0] + 1 = 1 (minimum)
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| 0 | 1 | inf | inf | inf | inf | inf | inf | inf |
1 - coins[1] = 1 - 2 < 0
coins = {1, 2, 3}
current table
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| 0 | 1 | inf | inf | inf | inf | inf | inf | inf |
2 - coins[0] = 2 - 1 = 1
table[1] = 1
table[2] = inf
table[1] + 1 = 2 (minimum)
update the table
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 2 | inf | inf | inf | inf | inf | inf |
2 - coins[1] = 2 - 2 = 0
table[0] = 0
table[2] = 2
table[0] + 1 = 1 (minimum)
update the table
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 1 | inf | inf | inf | inf | inf | inf |
2 - coins[2] = 2 - 3 < 0
current table
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 1 | inf | inf | inf | inf | inf | inf |
| target > | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| coins/options | 0 | 1 | 1 | inf | inf | inf | inf | inf | inf |
| change for coins[0] | - | 1 | 2 | 2 | 2 | 3 | 3 | 3 | 4 |
| change for coins[1] | - | - | 1 | 2 | 2 | 2 | 3 | 3 | 3 |
| change for coins[2] | - | - | - | 1 | 2 | 2 | 2 | 3 | 3 |
| final look | 0 | 1 | 1 | 1 | 2 | 2 | 2 | 3 | 3 |