Return the fewest coins needed to make up amount, or -1 if it cannot be done. You have unlimited coins of each denomination.
Each coin is an edge from remainder r to r − c. The first time BFS reaches 0, the depth is the fewest coins.
1function coinChange(coins: number[], amount: number): number {2if (amount === 0) return 0;3const seen = new Set([amount]);4let queue = [amount], depth = 0;5while (queue.length) {6depth++;7const next: number[] = [];8for (const r of queue)9for (const c of coins) {10const rest = r - c;11if (rest === 0) return depth;12if (rest > 0 && !seen.has(rest)) { seen.add(rest); next.push(rest); }13}14queue = next;15}16return -1;17}
Start BFS from 11.
Space: play/pause · ←/→: step