-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcoin_change.js
78 lines (62 loc) · 1.81 KB
/
coin_change.js
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
70
71
72
73
74
75
76
77
78
// To run: node coin_change.js
//
// https://leetcode.com/problems/coin-change/
//
// See "dynamic programming - top down" section here for full explanation:
// https://leetcode.com/problems/coin-change/solution
// Naive version (slow for cents=221)
function minCoins(cents) {
if (cents <= 0) {
return 0;
}
const coins = [25, 10, 1];
let minValue = Number.MAX_VALUE;
for (const coin of coins) {
// Can't use this coin if the value is lower
if (coin > cents) {
continue;
}
// Remove one copy of coin, and figure out
// min coins for reduced amount.
const value = minCoins(cents - coin) + 1;
// Set min_value
minValue = Math.min(minValue, value);
}
return minValue;
}
// Using top-down dynamic programming (recursion with memoization)
//
// Runtime: O(numcoins * numcents)
// Each of memo[i] to memo[numcents+1] will only be calculated once.
// When memo[i] is calculated, it will take numcoins operations.
function minCoins(cents) {
// memo[i] contains min coins needed to make value i
const memo = [0];
function minCoinsHelper(cents) {
if (cents <= 0) {
return 0;
}
const coins = [25, 10, 1];
let minValue = Number.MAX_VALUE;
for (const coin of coins) {
// Can't use this coin if the value is lower
if (coin > cents) {
continue;
}
// Remove one copy of coin, and figure out
// min coins for reduced amount.
const value = memo[cents - coin] == null ? minCoinsHelper(cents - coin) : memo[cents - coin];
// Set min_value
minValue = Math.min(minValue, value + 1);
}
memo[cents] = minValue;
return minValue;
}
return minCoinsHelper(cents);
}
// Test cases
console.log(minCoins(0))
console.log(minCoins(6))
console.log(minCoins(31))
console.log(minCoins(55))
console.log(minCoins(221))