Skip to content

Commit

Permalink
refactor: feat: 322. Coin Change
Browse files Browse the repository at this point in the history
  • Loading branch information
gwbaik9717 committed Jan 1, 2025
1 parent 70f3ef1 commit 6eb0ac0
Showing 1 changed file with 8 additions and 18 deletions.
26 changes: 8 additions & 18 deletions coin-change/gwbaik9717.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,23 @@
// n: amount m: length of coins
// Time complexity: O(n * m) + O(mlogm)
// Space complexity: O(n * m)
// Space complexity: O(n)

/**
* @param {number[]} coins
* @param {number} amount
* @return {number}
*/
var coinChange = function (coins, amount) {
const dp = Array.from({ length: coins.length + 1 }, () =>
Array.from({ length: amount + 1 }, () => Infinity)
);
coins.sort((a, b) => a - b);

for (let i = 0; i < coins.length + 1; i++) {
dp[i][0] = 0;
}
const dp = Array.from({ length: amount + 1 }, () => Infinity);
dp[0] = 0;

for (let i = 1; i <= amount; i++) {
for (let j = 1; j <= coins.length; j++) {
const coin = coins[j - 1];

if (i >= coin) {
dp[j][i] = Math.min(dp[j][i], 1 + dp[j][i - coin]);
}
coins.sort((a, b) => a - b);

dp[j][i] = Math.min(dp[j][i], dp[j - 1][i]);
for (const coin of coins) {
for (let i = coin; i <= amount; i++) {
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
}
}

return dp.at(-1).at(-1) === Infinity ? -1 : dp.at(-1).at(-1);
return dp.at(-1) === Infinity ? -1 : dp.at(-1);
};

0 comments on commit 6eb0ac0

Please sign in to comment.