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