The Problem
I was recently asked to calculate the money owed amongst a group of people who went on a trip together and came upon an interesting problem: given that you know the amounts that each person owes another, what is a general algorithm to consolidate the debts between people so that only the minimum number of payments needs to be made? Take this as an example:
- Mike owes John 100
- John owes Rachel 200
- Mike owes Rachel 400
We can remove a payment between Mike and John by reformulating the debts like this:
- Mike owes John 0
- John owes Rachel 100
- Mike owes Rachel 500
I did the math by hand since it was easy enough, but then the programmer in me was itching to figure out a general algorithm to do it for an arbitrarily large group. This seems like a graph algorithm to me, so I'll reformulate this as a graph:
Viewed as a Graph
- The vertices are the people in the group
- The edges are directed and weighted by the amount owed. For example, an edge from Mike to Rachel with weight 500 means that Mike owes Rachel 500.
- Constraint: the net sum of weights for each node must remain unchanged.
- The goal is to find a graph with the minimum number of edges that still satisfy the constraint.