|
| 1 | +function change(coins, amount){ |
| 2 | + let combinations = new Array(amount + 1).fill(0) |
| 3 | + combinations[0] = 1 |
| 4 | + |
| 5 | + for (let i=0; i<coins.length; i++){ |
| 6 | + const coin = coins[i] |
| 7 | + |
| 8 | + for (let j = coin; j < amount + 1; j++){ |
| 9 | + combinations[j] += combinations[j - coin]; |
| 10 | + } |
| 11 | + // Uncomment the line below to see the state of combinations for each coin |
| 12 | + // printAmount(combinations); |
| 13 | + } |
| 14 | + return combinations[amount]; |
| 15 | +} |
| 16 | + |
| 17 | +function minimumCoins(coins, amount) { |
| 18 | + //minimumCoins[i] will store the minimum coins needed for amount i |
| 19 | + let minimumCoins = new Array(amount + 1).fill(0); |
| 20 | + |
| 21 | + minimumCoins[0] = 0; |
| 22 | + |
| 23 | + for (let i = 1; i < amount + 1; i++) { |
| 24 | + minimumCoins[i] = Number.MAX_SAFE_INTEGER; |
| 25 | + } |
| 26 | + for (let i = 1; i < amount + 1; i++) { |
| 27 | + for (let j=0; j < coins.length; j++) { |
| 28 | + const coin = coins[j]; |
| 29 | + if (coin <= i) { |
| 30 | + sub_res = minimumCoins[i - coin]; |
| 31 | + if (sub_res != Number.MAX_SAFE_INTEGER && sub_res + 1 < minimumCoins[i]) |
| 32 | + minimumCoins[i] = sub_res + 1; |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + // Uncomment the line below to see the state of combinations for each coin |
| 37 | + //printAmount(minimumCoins); |
| 38 | + return minimumCoins[amount]; |
| 39 | +} |
| 40 | + |
| 41 | +// A basic print method which prints all the contents of the array |
| 42 | +function printAmount(arr) { |
| 43 | + for (let i = 0; i < arr.length; i++) { |
| 44 | + console.log(arr[i] + " "); |
| 45 | + } |
| 46 | + console.log("\n"); |
| 47 | +} |
| 48 | + |
| 49 | +function main() { |
| 50 | + const amount = 12 |
| 51 | + const coins = [2, 4, 5] |
| 52 | + console.log("Number of combinations of getting change for " + amount + " is: " + change(coins,amount)) |
| 53 | + console.log("Minimum number of coins required for amount :" + amount + " is: " + minimumCoins(coins, amount)); |
| 54 | +} |
| 55 | + |
| 56 | +main() |
0 commit comments