Skip to content

Commit 4b76b49

Browse files
authored
Added CoinChange Algorithm (TheAlgorithms#260)
* Added CoinChange Algorithm * Minor Changes * Minor Changes * Minor Changes
1 parent 3277751 commit 4b76b49

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Dynamic-Programming/CoinChange.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
function change (coins, amount) {
2+
const 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+
}
12+
return combinations[amount]
13+
}
14+
15+
function minimumCoins (coins, amount) {
16+
// minimumCoins[i] will store the minimum coins needed for amount i
17+
const minimumCoins = new Array(amount + 1).fill(0)
18+
19+
minimumCoins[0] = 0
20+
21+
for (let i = 1; i < amount + 1; i++) {
22+
minimumCoins[i] = Number.MAX_SAFE_INTEGER
23+
}
24+
for (let i = 1; i < amount + 1; i++) {
25+
for (let j = 0; j < coins.length; j++) {
26+
const coin = coins[j]
27+
if (coin <= i) {
28+
const subRes = minimumCoins[i - coin]
29+
if (subRes !== Number.MAX_SAFE_INTEGER && subRes + 1 < minimumCoins[i]) {
30+
minimumCoins[i] = subRes + 1
31+
}
32+
}
33+
}
34+
}
35+
return minimumCoins[amount]
36+
}
37+
38+
function main () {
39+
const amount = 12
40+
const coins = [2, 4, 5]
41+
console.log('Number of combinations of getting change for ' + amount + ' is: ' + change(coins, amount))
42+
console.log('Minimum number of coins required for amount :' + amount + ' is: ' + minimumCoins(coins, amount))
43+
}
44+
45+
main()

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy