|
| 1 | +// Time Complexity: O(amount * coins.length) |
| 2 | +// Space Complexity: O(amount) |
| 3 | + |
| 4 | +var coinChange = function (coins, amount) { |
| 5 | + // if the amount is 0, no coins are needed |
| 6 | + if (amount === 0) return 0; |
| 7 | + |
| 8 | + // a queue to hold the current amount and coins used to reach that amount |
| 9 | + let queue = [{ amount: 0, steps: 0 }]; |
| 10 | + |
| 11 | + // a set to keep track of visited amounts to avoid revisiting them |
| 12 | + let visited = new Set(); |
| 13 | + visited.add(0); |
| 14 | + |
| 15 | + // start the BFS loop |
| 16 | + while (queue.length > 0) { |
| 17 | + // dequeue the first element |
| 18 | + let { amount: currentAmount, steps } = queue.shift(); |
| 19 | + |
| 20 | + // iterate through each coin |
| 21 | + for (let coin of coins) { |
| 22 | + // calculate the new amount by adding the coin to the current amount |
| 23 | + let newAmount = currentAmount + coin; |
| 24 | + |
| 25 | + // if the new amount equals the target amount, return the number of steps plus one |
| 26 | + if (newAmount === amount) { |
| 27 | + return steps + 1; |
| 28 | + } |
| 29 | + |
| 30 | + // if the new amount is less than the target amount and hasn't been visited, enqueue it |
| 31 | + if (newAmount < amount && !visited.has(newAmount)) { |
| 32 | + queue.push({ amount: newAmount, steps: steps + 1 }); |
| 33 | + visited.add(newAmount); |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + // if the loop completes without finding the target amount, return -1 |
| 39 | + return -1; |
| 40 | +}; |
0 commit comments