-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathminTransfers.cpp
More file actions
32 lines (32 loc) · 986 Bytes
/
minTransfers.cpp
File metadata and controls
32 lines (32 loc) · 986 Bytes
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
class Solution {
public:
int minTransfers(vector<vector<int>>& transactions) {
int res = INT_MAX;
unordered_map<int, int> m;
for (auto t : transactions) {
m[t[0]] -= t[2];
m[t[1]] += t[2];
}
vector<int> accnt;
for (auto a : m) {
if (a.second != 0) accnt.push_back(a.second);
}
helper(accnt, 0, 0, res);
return res;
}
void helper(vector<int>& accnt, int start, int cnt, int& res) {
int n = accnt.size();
while (start < n && accnt[start] == 0) ++start;
if (start == n) {
res = min(res, cnt);
return;
}
for (int i = start + 1; i < n; ++i) {
if ((accnt[i] < 0 && accnt[start] > 0) || (accnt[i] > 0 && accnt[start] < 0)) {
accnt[i] += accnt[start];
helper(accnt, start + 1, cnt + 1, res);
accnt[i] -= accnt[start];
}
}
}
};