Skip to content

Commit 6f1fecb

Browse files
committed
Update Backtracking/465_Optimal_Account_Balancing.java
1 parent 6ad5517 commit 6f1fecb

File tree

1 file changed

+22
-20
lines changed

1 file changed

+22
-20
lines changed
Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,49 @@
11
class Solution {
22
public int minTransfers(int[][] transactions) {
3-
Map<Integer, Integer> balances = new HashMap<>();
3+
Map<Integer, Integer> balanceMap = new HashMap<>();
44

55
for (int[] transaction : transactions) {
66
int from = transaction[0];
77
int to = transaction[1];
88
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);
1212
}
1313

1414
int idx = 0;
15-
int[] debts = new int[balances.size()];
15+
int[] balances = new int[balanceMap.size()];
1616

17-
for (int debt : balances.values()) {
18-
debts[idx] = debt;
17+
for (int balance : balanceMap.values()) {
18+
balances[idx] = balance;
1919
++idx;
2020
}
2121

22-
return dfs(debts, 0);
22+
return minTransfersHelper(balances, 0);
2323
}
2424

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; }
2927

30-
if (balances[start] == 0) {
31-
return dfs(balances, start + 1);
28+
if (balances[idx] == 0) {
29+
return minTransfersHelper(balances, idx + 1);
3230
}
3331

34-
int minTransactions = Integer.MAX_VALUE;
35-
int currBalance = balances[start];
32+
int currBalance = balances[idx];
33+
int minNumberOfTransactions = Integer.MAX_VALUE;
3634

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+
}
3941

4042
balances[i] += currBalance;
41-
minTransactions = Math.min(minTransactions, 1 + dfs(balances, start + 1));
43+
minNumberOfTransactions = Math.min(minNumberOfTransactions, 1 + minTransfersHelper(balances, idx + 1));
4244
balances[i] -= currBalance;
4345
}
4446

45-
return minTransactions;
47+
return minNumberOfTransactions;
4648
}
4749
}

0 commit comments

Comments
 (0)