Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Coin Change Problem solution in JS #2132

Merged
merged 1 commit into from
Mar 6, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Coin_Change/Coin_Change.js
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