Skip to content

Commit f5cfc08

Browse files
committed
Coin Change solution
1 parent 57b9908 commit f5cfc08

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

coin-change/kimyoung.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
var coinChange = function (coins, amount) {
2+
// create a dp array that stores the minimum amount of coins used for each amount leading up to the target amount
3+
// fill with array with amount + 1 as a default
4+
const dp = [0, ...new Array(amount).fill(amount + 1)];
5+
6+
// loop through the coins
7+
for (const coin of coins) {
8+
// for each amount, assess how the current coin can modify the existing value within the dp array by comparing the min value
9+
for (let i = 1; i <= amount; i++) {
10+
// only works if coin is less than or equal to the assessing amount
11+
if (coin <= i) {
12+
// min comparison
13+
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
14+
}
15+
}
16+
}
17+
// check target amount in dp array to see if it's the default value
18+
// if it's default value, it means coin combination cannot lead up to target amount
19+
// if it's not default value, that is the minimum required coin change to lead up to target amount
20+
return dp[amount] === amount + 1 ? -1 : dp[amount];
21+
};
22+
23+
// time - O(a * c) loops through amount * loops through coin
24+
// space - O(a) depends on the size of amount

0 commit comments

Comments
 (0)