Optimal Account Balancing Problem
Description
LeetCode Problem 465.
You are given an array of transactions transactions where transactions[i] = [from_i, to_i, amount_i] indicates that the person with ID = from_i gave amount_i $ to the person with ID = to_i.
Return the minimum number of transactions required to settle the debt.
Example 1:
Input: transactions = [[0,1,10],[2,0,5]]
Output: 2
Explanation:
Person #0 gave person #1 $10.
Person #2 gave person #0 $5.
Two transactions are needed. One way to settle the debt is person #1 pays person #0 and #2 $5 each.
Example 2:
Input: transactions = [[0,1,10],[1,0,1],[1,2,5],[2,0,5]]
Output: 1
Explanation:
Person #0 gave person #1 $10.
Person #1 gave person #0 $1.
Person #1 gave person #2 $5.
Person #2 gave person #0 $5.
Therefore, person #1 only need to give person #0 $4, and all debt is settled.
Constraints:
1 <= transactions.length <= 8transactions[i].length == 30 <= from_i, to_i < 12from_i != to_i1 <= amount_i <= 100
Solution
Approach: Net Balances + Subset DP
Only net balances matter. Who paid whom in the past does not matter. All that counts is how much each person is up or down overall. Add each amount to the receiver's balance and subtract it from the giver's. People with a balance of 0 are already settled and drop out. That leaves m ≤ 12 nonzero balances, which add up to 0.
Settling one group. Take any group of people whose balances add up to 0. It can always be settled with size - 1 transfers: line the people up, and let each one pass their whole running balance to the next. Each transfer brings one more person to zero, and the last person ends at zero automatically. A group can never do better than size - 1 unless it splits into smaller groups that each sum to 0 on their own. Every transfer connects two people, so with fewer than size - 1 transfers the group falls apart into separate pieces, and each piece must settle by itself.
So the answer is m minus the largest number of zero-sum groups the people can be split into. Compute it with a DP over subsets. Let best[mask] be the fewest transfers that settle the people in mask among themselves:
- if the balances in
maskdo not add up to0, it cannot be settled alone:best[mask] = ∞; - otherwise start from
popcount(mask) - 1, and try every split ofmaskinto a non-emptysuband the rest:best[mask] = min(best[sub] + best[mask ^ sub]). Splits where either part does not sum to0are∞and never win.
total[mask] is built from total[mask without its lowest person], so each sum costs O(1). The answer is best[all people]. In Example 1 the balances are -5, +10, -5. They cannot be split into smaller zero-sum groups, so the answer is 3 - 1 = 2.
Complexity: O(3m) time for the loops over masks and their submasks, where m ≤ 12 is the number of people with a nonzero balance. O(2m) space.
class Solution:
def minTransfers(self, transactions: List[List[int]]) -> int:
balance = [0] * 12
for giver, receiver, amount in transactions:
balance[giver] -= amount
balance[receiver] += amount
debts = [x for x in balance if x != 0] # people who are already even drop out
m = len(debts)
full = (1 << m) - 1
INF = float("inf")
total = [0] * (1 << m) # total[mask] = sum of the balances in mask
best = [INF] * (1 << m) # best[mask] = fewest transfers to settle mask on its own
best[0] = 0
for mask in range(1, full + 1):
low = mask & -mask
total[mask] = total[mask ^ low] + debts[low.bit_length() - 1]
if total[mask] != 0:
continue # a group can only settle among itself if its balances cancel out
best[mask] = bin(mask).count("1") - 1 # a chain of payments always works
sub = (mask - 1) & mask
while sub > 0: # or split it into two groups that each settle on their own
best[mask] = min(best[mask], best[sub] + best[mask ^ sub])
sub = (sub - 1) & mask
return best[full]