10000 Add `465_Optimal_Account_Balancing.java` · seanprashad/leetcode-patterns@b454e4d · GitHub
[go: up one dir, main page]

Skip to content

Commit b454e4d

Browse files
committed
Add 465_Optimal_Account_Balancing.java
1 parent 2279012 commit b454e4d

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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

Comments
 (0)
0