Minimize Cash Flow among a given set of friends who have borrowed money from each other
Pattern: Candy and assign cookies
Only each person's net balance matters. Repeatedly let the person who is owed the most be paid by the person who owes the most, by the smaller of the two amounts; that settles at least one of them, so there are at most n - 1 payments.
The problem
owes[i][j] is the money person i owes person j. Settle all debts and return the payments [from, to, amount] in
the order this rule makes them: each time, the person with the largest debt pays the person owed the most (lowest number
on ties), by the smaller of the two amounts. Stop when everyone is settled. The linked page could not be read when this guide was written, so the rules below are this guide's own statement of the task.
Think first
- Does it matter who owes whom originally?
- What does one payment between the biggest debtor and the biggest creditor achieve?
- How many payments can there be?
Hints
Brute force, and why it fails
Pay every original debt as it stands: up to n² payments.
The key insight
Reducing to net balances and always matching the two extremes settles one person per payment, so the list stays short.
Dry run
| net | -3000 -4000 7000 |
|---|
owes[0][1] = 1000, owes[0][2] = 2000, owes[1][2] = 5000. Net: person 0 is -3000, person 1 is -4000, person 2 is +7000.
The plan
net[j] += owes[i][j]; net[i] -= owes[i][j]
loop: cred = argmax net; debt = argmin net (lowest index on ties)
if net[cred] == 0: stop
amount = min(net[cred], -net[debt]); record [debt, cred, amount]; update both
Complexity
- Time
O(n²)- Space
O(n)
Building balances is O(n²); each of at most n payments scans n people.
Edge cases
- Nobody owes anything: no payments.
- A cycle of equal debts cancels completely.
- One person.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<List<Integer>> minCashFlow(int[][] owes) {
int n = owes.length;
int[] net = new int[n]; // money each person should end up receiving
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
net[j] += owes[i][j]; // i owes j
net[i] -= owes[i][j];
}
List<List<Integer>> out = new ArrayList<>();
while (true) {
int cred = 0, debt = 0;
for (int i = 1; i < n; i++) {
if (net[i] > net[cred]) cred = i; // the biggest creditor (lowest index on ties)
if (net[i] < net[debt]) debt = i; // the biggest debtor (lowest index on ties)
}
if (net[cred] == 0 || net[debt] == 0) return out; // everyone is settled
int amount = Math.min(net[cred], -net[debt]);
out.add(Arrays.asList(debt, cred, amount)); // settles at least one of the two
net[cred] -= amount;
net[debt] += amount;
}
}
}C++
class Solution {
public:
vector<vector<int>> minCashFlow(vector<vector<int>>& owes) {
int n = static_cast<int>(owes.size());
vector<int> net(n, 0); // money each person should end up receiving
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
net[j] += owes[i][j]; // i owes j
net[i] -= owes[i][j];
}
vector<vector<int>> out;
while (true) {
int cred = 0, debt = 0;
for (int i = 1; i < n; i++) {
if (net[i] > net[cred]) cred = i; // the biggest creditor (lowest index on ties)
if (net[i] < net[debt]) debt = i; // the biggest debtor (lowest index on ties)
}
if (net[cred] == 0 || net[debt] == 0) return out; // everyone is settled
int amount = min(net[cred], -net[debt]);
out.push_back(vector<int>{debt, cred, amount}); // settles at least one of the two
net[cred] -= amount;
net[debt] += amount;
}
}
};Python
class Solution:
def minCashFlow(self, owes: list[list[int]]) -> list[list[int]]:
n = len(owes)
net = [0] * n # money each person should end up receiving
for i in range(n):
for j in range(n):
net[j] += owes[i][j] # i owes j
net[i] -= owes[i][j]
out = []
while True:
cred = max(range(n), key=lambda i: (net[i], -i)) # the biggest creditor, lowest index on ties
debt = min(range(n), key=lambda i: (net[i], i)) # the biggest debtor, lowest index on ties
if net[cred] == 0 or net[debt] == 0:
return out # everyone is settled
amount = min(net[cred], -net[debt])
out.append([debt, cred, amount]) # settles at least one of the two
net[cred] -= amount
net[debt] += amountCommon mistakes
- Paying the original debts without netting.
- Choosing the debtor and creditor without a fixed tie rule, so the output order changes.