-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0322.js
More file actions
69 lines (56 loc) · 1.78 KB
/
0322.js
File metadata and controls
69 lines (56 loc) · 1.78 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
68
69
/**
* @param {number[]} coins
* @param {number} amount
* @return {number}
*/
var coinChange = function(coins, amount) {
// store change and depth
// the depth is the number of coins
// initial case is zero change with zero coins
let coin_change_depth = {0: 0}
// BFS Queue
let bfs_coin_queue = [0]
while (bfs_coin_queue.length) {
let coin_change = bfs_coin_queue.shift()
// Reached amount via bfs, guaranteed least nr coins
if (coin_change === amount) return coin_change_depth[amount]
for (const coin of coins) {
let next_payment = coin_change + coin
// skip overshoot
if (next_payment > amount) continue
// skip payments already tried (part of BFS)
if (next_payment in coin_change_depth) continue
// append the dict and queue
coin_change_depth[next_payment] = coin_change_depth[coin_change] + 1
bfs_coin_queue.push(next_payment)
}
}
return -1
};
/**
* @param {number[]} coins
* @param {number} amount
* @return {number}
*/
var coinChange = function(coins, amount) {
let max = amount+1;
let dp_cache = new Array(amount+1, max);
// base case
dp_cache[0] = 0;
for(let change = 1; change <= amount; change++)
{
let min_coins = max;
for(const coin of coins)
{
let prev_change = change - coin;
if(prev_change < 0) continue;
if(dp_cache[prev_change] + 1 < min_coins)
{
min_coins = dp_cache[prev_change] +1;
}
}
dp_cache[change] = min_coins;
}
if(dp_cache[amount] === max) return -1;
return dp_cache[amount];
};