Optimal Account Balancing
A group of friends lent each other money. Each entry in transactions is [giver, receiver, amount]: the person with id giver gave amount dollars to the person with id receiver.
Return the fewest transfers needed to settle every debt, so that everyone ends up even.
Example 1
Input: transactions = [[0, 1, 10], [2, 0, 5]] Output: 2
Person 0 gave 10 and received 5, so they're owed 5. Person 1 owes 10 and person 2 is owed 5. Person 1 can pay 5 to person 0 and 5 to person 2: two transfers.
Example 2
Input: transactions = [[0, 1, 10], [1, 0, 1], [1, 2, 5], [2, 0, 5]] Output: 1
Person 0 is owed 4, person 1 owes 4 and person 2 is even. One transfer of 4 from person 1 to person 0 settles everything.
Constraints
1 <= transactions.length <= 80 <= giver, receiver < 12, andgiver != receiver1 <= amount <= 100
Approach
First, reduce the transactions to each person's net balance: positive if they're owed money, negative if they owe it. People with a balance of zero are already even and can be dropped. The history no longer matters, only these balances.
A greedy rule, like always settling the largest debt with the largest credit, isn't always optimal. Instead, search. Take the first person with a nonzero balance and settle their entire balance in one transfer with someone whose balance has the opposite sign. That person is now even, and the other person's balance changes by the same amount. Try every such partner, recurse on the remaining people and keep the smallest count. Two pruning rules keep the search small: skip people who are already even, and only try each distinct partner balance once, since equal balances lead to identical subproblems.
Steps
- Compute each person's net balance and keep only the nonzero ones.
- Define
settle(start): skip past people whose balance is 0. If everyone is even, return 0. - For each later person with the opposite sign and a balance you haven't tried, add
debts[start]to their balance, take1 + settle(start + 1), then undo the change. - Return the smallest result, starting from
settle(0).
from collections import defaultdict
from typing import List
def min_transfers(transactions: List[List[int]]) -> int:
balance = defaultdict(int)
for giver, receiver, amount in transactions:
balance[giver] += amount # the giver is owed this much
balance[receiver] -= amount
debts = [b for b in balance.values() if b != 0]
def settle(start: int) -> int:
while start < len(debts) and debts[start] == 0:
start += 1 # skip people who are already even
if start == len(debts):
return 0
best = float("inf")
tried = set()
for i in range(start + 1, len(debts)):
# settle start's whole balance with someone on the other side, once per distinct amount
if debts[i] * debts[start] < 0 and debts[i] not in tried:
tried.add(debts[i])
debts[i] += debts[start]
best = min(best, 1 + settle(start + 1))
debts[i] -= debts[start]
return best
return settle(0)Complexity
- Time:
O(n!)in the worst case, wherenis the number of people with a nonzero balance. The pruning makes it much faster in practice, andnis at most 12 here. - Space:
O(n)for the balances and the recursion.
Common mistakes
- Settling the largest debt with the largest credit first. It can miss groups of people whose balances cancel out exactly, and those are what save transfers.
- Counting transactions instead of working from net balances. Many transactions can cancel out completely.
- Not undoing the change to
debts[i]after each recursive call, which corrupts the balances for the next partner you try.