forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoinChange.js
More file actions
Latest commit
33 lines (33 loc) · 898 Bytes
/
Copy pathCoinChange.js
File metadata and controls
33 lines (33 loc) · 898 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* @params {Array} coins
* @params {Number} amount
*/
exportconstchange=(coins,amount)=>{
// Create and initialize the storage
constcombinations=newArray(amount+1).fill(0)
combinations[0]=1
// Determine the direction of smallest sub-problem
for(leti=0;i<coins.length;i++){
// Travel and fill the combinations array
for(letj=coins[i];j<combinations.length;j++){
combinations[j]+=combinations[j-coins[i]]
}
}
returncombinations[amount]
}
/**
* @params {Array} coins
* @params {Number} amount
*/
exportconstcoinChangeMin=(coins,amount)=>{
constmap={0: 1}
for(leti=1;i<=amount;i++){
letmin=Infinity
for(constcoinofcoins){
if(i<coin)continue
min=Math.min(min,1+map[i-coin])
}
map[i]=min
}
returnmap[amount]===Infinity ? -1 : map[amount]-1
}