-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Coin Change Problem solution in JS (#2132)
- Loading branch information
1 parent
1d4f599
commit 9d6c263
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 | ||
|