diff --git a/coin-change/gwbaik9717.js b/coin-change/gwbaik9717.js index e2b0b78a2..752060ad9 100644 --- a/coin-change/gwbaik9717.js +++ b/coin-change/gwbaik9717.js @@ -1,6 +1,6 @@ // 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 @@ -8,26 +8,16 @@ * @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); };