| 5 | 5 | |
| 6 | 6 | export class Change { |
| 7 | 7 | calculate(coinArray, target) { |
| 8 | | throw new Error('Remove this line and implement the function'); |
| 8 | // Edge Case: target is negative |
| 9 | if (target < 0) { |
| 10 | throw new Error('Negative totals are not allowed.'); |
| 11 | } |
| 12 | |
| 13 | // Edge Case: target is 0 |
| 14 | if (target === 0) { |
| 15 | return []; |
| 16 | } |
| 17 | |
| 18 | // Edge Case: no coins available |
| 19 | if (!coinArray || coinArray.length === 0) { |
| 20 | throw new Error(`The total ${target} cannot be represented in the given currency.`); |
| 21 | } |
| 22 | |
| 23 | // Filter out non-positive coins and sort in descending order for optimization |
| 24 | const validCoins = coinArray.filter(coin => coin > 0).sort((a, b) => b - a); |
| 25 | |
| 26 | // Edge Case: no valid coins after filtering |
| 27 | if (validCoins.length === 0) { |
| 28 | throw new Error(`The total ${target} cannot be represented in the given currency.`); |
| 29 | } |
| 30 | |
| 31 | // Dynamic programming approach to find minimum coins |
| 32 | const dp = new Array(target + 1).fill(Infinity); |
| 33 | const coinUsed = new Array(target + 1).fill(0); |
| 34 | dp[0] = 0; |
| 35 | |
| 36 | for (let i = 1; i <= target; i++) { |
| 37 | for (const coin of validCoins) { |
| 38 | if (coin <= i && dp[i - coin] !== Infinity) { |
| 39 | if (dp[i - coin] + 1 < dp[i]) { |
| 40 | dp[i] = dp[i - coin] + 1; |
| 41 | coinUsed[i] = coin; |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | // Edge Case: target amount cannot be made with given coins |
| 48 | if (dp[target] === Infinity) { |
| 49 | throw new Error(`The total ${target} cannot be represented in the given currency.`); |
| 50 | } |
| 51 | |
| 52 | // Reconstruct the solution |
| 53 | const result = []; |
| 54 | let remaining = target; |
| 55 | while (remaining > 0) { |
| 56 | const coin = coinUsed[remaining]; |
| 57 | result.push(coin); |
| 58 | remaining -= coin; |
| 59 | } |
| 60 | |
| 61 | // Return coins sorted in ascending order |
| 62 | return result.sort((a, b) => a - b); |
| 9 | 63 | } |
| 10 | 64 | } |
| 65 | |
| 66 | // Handled Edge Cases: target is negative, target is 0, no coins available, no valid coins after filtering, target amount cannot be made with given coins |