forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
optimal-account-balancing.py
37 lines (33 loc) · 1.08 KB
/
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
# Time: O(n * 2^n), n is the size of the debt.
# Space: O(n * 2^n)
class Solution(object):
def minTransfers(self, transactions):
"""
:type transactions: List[List[int]]
:rtype: int
"""
account = collections.defaultdict(int)
for transaction in transactions:
account[transaction[0]] += transaction[2]
account[transaction[1]] -= transaction[2]
debt = []
for v in account.values():
if v:
debt.append(v)
if not debt:
return 0
n = 1 << len(debt)
dp, subset = [float("inf")] * n, []
for i in xrange(1, n):
net_debt, number = 0, 0
for j in xrange(len(debt)):
if i & 1 << j:
net_debt += debt[j]
number += 1
if net_debt == 0:
dp[i] = number - 1
for s in subset:
if (i & s) == s:
dp[i] = min(dp[i], dp[s] + dp[i - s])
subset.append(i)
return dp[-1]