-
Notifications
You must be signed in to change notification settings - Fork 368
/
Copy pathOptimal Account Balancing.java
73 lines (63 loc) · 2.26 KB
/
Optimal Account Balancing.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class Solution {
int min = Integer.MAX_VALUE;
public int minTransfers(int[][] transactions) {
Map<Integer, Integer> account = new HashMap<>();
for (int[] transaction : transactions) {
int amount = transaction[2];
account.put(transaction[0], account.getOrDefault(transaction[0], 0) + amount);
account.put(transaction[1], account.getOrDefault(transaction[1], 0) - amount);
}
LinkedList<Integer> posBalance = new LinkedList<>();
LinkedList<Integer> negBalance = new LinkedList<>();
for (Integer key : account.keySet()) {
if (account.get(key) < 0) {
negBalance.add(account.get(key));
}
else if (account.get(key) > 0) {
posBalance.add(account.get(key));
}
}
dfs(posBalance, negBalance, 0);
return min;
}
private void dfs(List<Integer> posBalance, List<Integer> negBalance, int count) {
if (posBalance.size() == 0 || negBalance.size() == 0) {
min = Math.min(count, min);
return;
}
if (count >= min) {
return;
}
int posAmount = posBalance.get(0);
for(int j = 0; j < negBalance.size(); j++) {
int negAmount = negBalance.get(j);
int newPositiveVal = Math.max(posAmount + negAmount, 0);
int newNegativeVal = Math.min(0, posAmount + negAmount);
if (newPositiveVal == 0){
posBalance.remove(0);
}
else {
posBalance.set(0, newPositiveVal);
}
if (newNegativeVal == 0){
negBalance.remove(j);
}
else{
negBalance.set(j, newNegativeVal);
}
dfs(posBalance, negBalance, count + 1);
if(newPositiveVal == 0){
posBalance.add(0, posAmount);
}
else {
posBalance.set(0, posAmount);
}
if(newNegativeVal == 0){
negBalance.add(j, negAmount);
}
else{
negBalance.set(j, negAmount);
}
}
}
}