Skip to content

Commit 6eb0ac0

Browse files
committed
refactor: feat: 322. Coin Change
1 parent 70f3ef1 commit 6eb0ac0

File tree

1 file changed

+8
-18
lines changed

1 file changed

+8
-18
lines changed

coin-change/gwbaik9717.js

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,23 @@
11
// n: amount m: length of coins
22
// Time complexity: O(n * m) + O(mlogm)
3-
// Space complexity: O(n * m)
3+
// Space complexity: O(n)
44

55
/**
66
* @param {number[]} coins
77
* @param {number} amount
88
* @return {number}
99
*/
1010
var coinChange = function (coins, amount) {
11-
const dp = Array.from({ length: coins.length + 1 }, () =>
12-
Array.from({ length: amount + 1 }, () => Infinity)
13-
);
14-
coins.sort((a, b) => a - b);
15-
16-
for (let i = 0; i < coins.length + 1; i++) {
17-
dp[i][0] = 0;
18-
}
11+
const dp = Array.from({ length: amount + 1 }, () => Infinity);
12+
dp[0] = 0;
1913

20-
for (let i = 1; i <= amount; i++) {
21-
for (let j = 1; j <= coins.length; j++) {
22-
const coin = coins[j - 1];
23-
24-
if (i >= coin) {
25-
dp[j][i] = Math.min(dp[j][i], 1 + dp[j][i - coin]);
26-
}
14+
coins.sort((a, b) => a - b);
2715

28-
dp[j][i] = Math.min(dp[j][i], dp[j - 1][i]);
16+
for (const coin of coins) {
17+
for (let i = coin; i <= amount; i++) {
18+
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
2919
}
3020
}
3121

32-
return dp.at(-1).at(-1) === Infinity ? -1 : dp.at(-1).at(-1);
22+
return dp.at(-1) === Infinity ? -1 : dp.at(-1);
3323
};

0 commit comments

Comments
 (0)