| 10 | 10 | * @returns {number[]} |
| 11 | 11 | */ |
| 12 | 12 | calculate(coinArray, target) { |
| 13 | | throw new Error('Remove this line and implement the function'); |
| 13 | // Edge Case: Negative target amount |
| 14 | if (target < 0) { |
| 15 | throw new Error('Negative totals are not allowed.'); |
| 16 | } |
| 17 | |
| 18 | // Edge Case: Zero target amount |
| 19 | if (target === 0) { |
| 20 | return []; |
| 21 | } |
| 22 | |
| 23 | // Edge Case: Empty coin denominations array |
| 24 | if (coinArray.length === 0) { |
| 25 | throw new Error(`The total ${target} cannot be represented in the given currency.`); |
| 26 | } |
| 27 | |
| 28 | // Filter out non-positive coins and sort in descending order for greedy approach attempt |
| 29 | const validCoins = coinArray.filter(coin => coin > 0).sort((a, b) => b - a); |
| 30 | |
| 31 | // Edge Case: No valid coins after filtering |
| 32 | if (validCoins.length === 0) { |
| 33 | throw new Error(`The total ${target} cannot be represented in the given currency.`); |
| 34 | } |
| 35 | |
| 36 | // Use dynamic programming to find the minimum number of coins |
| 37 | // dp[i] will store the minimum number of coins needed to make amount i |
| 38 | const dp = new Array(target + 1).fill(Infinity); |
| 39 | dp[0] = 0; |
| 40 | |
| 41 | // For tracking which coin was used to achieve the minimum at each amount |
| 42 | const coinUsed = new Array(target + 1).fill(0); |
| 43 | |
| 44 | // Fill dp array |
| 45 | for (let i = 1; i <= target; i++) { |
| 46 | for (const coin of validCoins) { |
| 47 | if (coin <= i && dp[i - coin] !== Infinity) { |
| 48 | if (dp[i - coin] + 1 < dp[i]) { |
| 49 | dp[i] = dp[i - coin] + 1; |
| 50 | coinUsed[i] = coin; |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | // Edge Case: Target amount cannot be made with given denominations |
| 57 | if (dp[target] === Infinity) { |
| 58 | throw new Error(`The total ${target} cannot be represented in the given currency.`); |
| 59 | } |
| 60 | |
| 61 | // Reconstruct the solution |
| 62 | const result = []; |
| 63 | let current = target; |
| 64 | while (current > 0) { |
| 65 | const coin = coinUsed[current]; |
| 66 | result.push(coin); |
| 67 | current -= coin; |
| 68 | } |
| 69 | |
| 70 | // Return coins sorted in ascending order as per examples |
| 71 | return result.sort((a, b) => a - b); |
| 14 | 72 | } |
| 15 | 73 | } |
| 74 | |
| 75 | // Handled Edge Cases: negative target amount, zero target amount, empty coin denominations array, no valid coins after filtering, target amount cannot be made with given denominations |