|
1 | 1 | // n: amount m: length of coins |
2 | 2 | // Time complexity: O(n * m) + O(mlogm) |
3 | | -// Space complexity: O(n * m) |
| 3 | +// Space complexity: O(n) |
4 | 4 |
|
5 | 5 | /** |
6 | 6 | * @param {number[]} coins |
7 | 7 | * @param {number} amount |
8 | 8 | * @return {number} |
9 | 9 | */ |
10 | 10 | 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; |
19 | 13 |
|
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); |
27 | 15 |
|
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); |
29 | 19 | } |
30 | 20 | } |
31 | 21 |
|
32 | | - return dp.at(-1).at(-1) === Infinity ? -1 : dp.at(-1).at(-1); |
| 22 | + return dp.at(-1) === Infinity ? -1 : dp.at(-1); |
33 | 23 | }; |
0 commit comments