Skip to content

Commit 935f123

Browse files
committed
Add coin-change solution
1 parent e7901f7 commit 935f123

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

coin-change/Jeehay28.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @param {number[]} coins
3+
* @param {number} amount
4+
* @return {number}
5+
*/
6+
7+
// TC : O(c*a), where c is the number of coins, and a is amount
8+
// SC : O(a) // dp array requires O(a) space
9+
10+
var coinChange = function (coins, amount) {
11+
// dynamic programming approach
12+
13+
// dp[amount] : the minimum number of coins
14+
// as a default, dp[0] = 0, for other amounts, dp[amount] = amount + 1 ()
15+
// [0, amount+1, amount+1, ...]
16+
const dp = [0, ...new Array(amount).fill(amount + 1)];
17+
18+
// start from coin because i - coin >= 0
19+
for (const coin of coins) {
20+
for (let i = coin; i <= amount; i++) {
21+
// dp[i] : not using the current coin
22+
// dp[i - coin] + 1 : using the current coin
23+
dp[i] = Math.min(dp[i - coin] + 1, dp[i]);
24+
}
25+
}
26+
27+
// dp[amount] === amount + 1 : that amount of money cannot be made up by any combination of the coins
28+
return dp[amount] < amount + 1 ? dp[amount] : -1;
29+
};
30+
31+

0 commit comments

Comments
 (0)