-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathCoinChange.js
More file actions
67 lines (54 loc) · 1.31 KB
/
CoinChange.js
File metadata and controls
67 lines (54 loc) · 1.31 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* @params {Array} coins
* @params {Number} amount
*/
export const change = (coins, amount) => {
if (!Array.isArray(coins)) {
throw new TypeError('Coins must be an array')
}
if (typeof amount !== 'number' || amount < 0) {
throw new TypeError('Amount must be a non-negative number')
}
if (amount === 0) {
return 1
}
if (coins.length === 0) {
return 0
}
const combinations = new Array(amount + 1).fill(0)
combinations[0] = 1
for (let i = 0; i < coins.length; i++) {
for (let j = coins[i]; j < combinations.length; j++) {
combinations[j] += combinations[j - coins[i]]
}
}
return combinations[amount]
}
/**
* @params {Array} coins
* @params {Number} amount
*/
export const coinChangeMin = (coins, amount) => {
if (!Array.isArray(coins)) {
throw new TypeError('Coins must be an array')
}
if (typeof amount !== 'number' || amount < 0) {
throw new TypeError('Amount must be a non-negative number')
}
if (amount === 0) {
return 0
}
if (coins.length === 0) {
return -1
}
const map = { 0: 0 }
for (let i = 1; i <= amount; i++) {
let min = Infinity
for (const coin of coins) {
if (i < coin) continue
min = Math.min(min, 1 + map[i - coin])
}
map[i] = min
}
return map[amount] === Infinity ? -1 : map[amount]
}