|
| 1 | +/** |
| 2 | + * 465. Optimal Account Balancing |
| 3 | + * https://leetcode.com/problems/optimal-account-balancing/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an array of transactions transactions where |
| 7 | + * transactions[i] = [fromi, toi, amounti] indicates that the person with ID = fromi |
| 8 | + * gave amounti $ to the person with ID = toi. |
| 9 | + * |
| 10 | + * Return the minimum number of transactions required to settle the debt. |
| 11 | + */ |
| 12 | + |
| 13 | +/** |
| 14 | + * @param {number[][]} transactions |
| 15 | + * @return {number} |
| 16 | + */ |
| 17 | +var minTransfers = function(transactions) { |
| 18 | + const balances = new Array(12).fill(0); |
| 19 | + |
| 20 | + for (const [from, to, amount] of transactions) { |
| 21 | + balances[from] -= amount; |
| 22 | + balances[to] += amount; |
| 23 | + } |
| 24 | + |
| 25 | + const debts = balances.filter(balance => balance !== 0); |
| 26 | + return helper(0, 0); |
| 27 | + |
| 28 | + function helper(index, count) { |
| 29 | + if (index === debts.length) return count; |
| 30 | + |
| 31 | + if (debts[index] === 0) return helper(index + 1, count); |
| 32 | + |
| 33 | + let minTransactions = Infinity; |
| 34 | + const currentDebt = debts[index]; |
| 35 | + |
| 36 | + for (let i = index + 1; i < debts.length; i++) { |
| 37 | + if (debts[i] * currentDebt < 0) { |
| 38 | + debts[i] += currentDebt; |
| 39 | + minTransactions = Math.min(minTransactions, helper(index + 1, count + 1)); |
| 40 | + debts[i] -= currentDebt; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return minTransactions; |
| 45 | + } |
| 46 | +}; |
0 commit comments