-
Notifications
You must be signed in to change notification settings - Fork 17
/
465-optimal-account-balancing.py
45 lines (41 loc) · 1.32 KB
/
465-optimal-account-balancing.py
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
from collections import defaultdict
class Solution:
def minTransfers(self, transactions: List[List[int]]) -> int:
people_balance = defaultdict(int)
for p, q, w in transactions:
people_balance[p] += w
people_balance[q] -= w
vals = []
for p, b in people_balance.items():
if b != 0:
vals.append(b)
res = float('inf')
def dfs(count, idx):
nonlocal res
if idx == len(vals):
res = min(res, count)
return
if vals[idx] == 0:
dfs(count, idx + 1)
return
for i in range(idx, len(vals)):
if i == idx:
continue
if vals[idx] * vals[i] >= 0:
continue
settle = vals[idx]
vals[idx] -= settle
vals[i] += settle
count += 1
dfs(count, idx + 1)
vals[idx] += settle
vals[i] -= settle
count -= 1
dfs(0, 0)
return res
# time O(n!)
# space O(n), due to recursion stack
# using dfs and backtracking and hashmap and backtracking with constraints
'''
1. we are enumerating every possible way to end the debt for each one
'''