From dcfb2cb2fd6b377bdfdeb0136a42cccafcbdc759 Mon Sep 17 00:00:00 2001 From: "Abhushan A. Joshi" <49617450+abhu-A-J@users.noreply.github.com> Date: Sat, 7 Mar 2020 00:04:31 +0530 Subject: [PATCH] Coin Change Problem solution in JS (#2132) --- Coin_Change/Coin_Change.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Coin_Change/Coin_Change.js diff --git a/Coin_Change/Coin_Change.js b/Coin_Change/Coin_Change.js new file mode 100644 index 0000000000..21065de664 --- /dev/null +++ b/Coin_Change/Coin_Change.js @@ -0,0 +1,29 @@ +/* +The Coin Change problem states that given an amount N, how +many possible ways are there to make the desired change using +unlimited supply of coins of given denominations. +*/ + +const coinChange = (denominations, amount) => { + + //make an array of length amount+1 and initialize with 0 + let dp_Definition = Array.from({ length: amount + 1 }, () => 0); + + //setting the base case for the definition + dp_Definition[0] = 1; + + for (let i = 0; i < denominations.length; i++) { + for (let j = denominations[i]; j < amount + 1; j++) { + dp_Definition[j] += dp_Definition[j - denominations[i]] + } + } + return dp_Definition[amount]; +} + +// I/O , O/P Examples + +console.log(coinChange([1, 5, 10, 25], 1)); //1 +console.log(coinChange([1, 5, 10, 25], 2)); //1 +console.log(coinChange([1, 5, 10, 25], 5)); //2 +console.log(coinChange([1, 5, 10, 25], 25)); //13 +