|
| 1 | +class Solution { |
| 2 | + public int minTransfers(int[][] transactions) { |
| 3 | + Map<Integer, Integer> balances = new HashMap<>(); |
| 4 | + |
| 5 | + for (int[] transaction : transactions) { |
| 6 | + int from = transaction[0]; |
| 7 | + int to = transaction[1]; |
| 8 | + int amount = transaction[2]; |
| 9 | + |
| 10 | + balances.put(from, balances.getOrDefault(from, 0) - amount); |
| 11 | + balances.put(to, balances.getOrDefault(to, 0) + amount); |
| 12 | + } |
| 13 | + |
| 14 | + int idx = 0; |
| 15 | + int[] debts = new int[balances.size()]; |
| 16 | + |
| 17 | + for (int debt : balances.values()) { |
| 18 | + debts[idx] = debt; |
| 19 | + ++idx; |
| 20 | + } |
| 21 | + |
| 22 | + return dfs(debts, 0); |
| 23 | + } |
| 24 | + |
| 25 | + private int dfs(int[] balances, int start) { |
| 26 | + if (start == balances.length) { |
| 27 | + return 0; |
| 28 | + } |
| 29 | + |
| 30 | + if (balances[start] == 0) { |
| 31 | + return dfs(balances, start + 1); |
| 32 | + } |
| 33 | + |
| 34 | + int minTransactions = Integer.MAX_VALUE; |
| 35 | + int currBalance = balances[start]; |
| 36 | + |
| 37 | + for (int i = start + 1; i < balances.length; i++) { |
| 38 | + if (currBalance * balances[i] >= 0) { continue; } |
| 39 | + |
| 40 | + balances[i] += currBalance; |
| 41 | + minTransactions = Math.min(minTransactions, 1 + dfs(balances, start + 1)); |
| 42 | + balances[i] -= currBalance; |
| 43 | + } |
| 44 | + |
| 45 | + return minTransactions; |
| 46 | + } |
| 47 | +} |
0 commit comments