Simple algorithm
In O (n) you can find how much money is waiting or will pay. Thus, you can simply create two lists: one for debit and one for credit, and then balance the heading of the two lists until they are empty. In the first example:
- Initial state: Debit: (A: 25), Credit: (B: 15, C: 10)
- First transaction, A: 15 β B: Debit: (A: 10), Credit: (C: 10)
- The second transaction, A: 10 β C: Debit :(), Credit :()
Operations define the boundaries of your schedule. For n persons involved, there will be no more than n-1 transactions = edges. Initially, the total length of both lists is n. At each step, at least one of the lists (debit / credit) becomes shorter by one, and in the last, both lists disappear immediately.
The problem is that, in general, this graph should not be similar to the original graph, which, as I understand it, is a requirement. (Is this? There are times when the optimal solution consists of adding new edges. Imagine that A and B and B have the same amount, A must pay C directly, but this edge is not in the debt schedule.)
Less transaction
If the goal is to build an equivalent schedule, you can search for lists of creditors and debtors (as indicated in the section above) for exact matches or for cases where the loan amount matches the debit of one person (or bypass). Find a package of beans . In other cases, you will have no choice but to split the streams, but even the simple algorithm above creates a graph that has fewer edges than there are people involved - at most.
EDIT . Thanks to j_random_hacker for indicating that a solution with edges less than n-1 is possible if there is a group of people whose total debt corresponds to a loan of another group of people: Then, the problem can be divided into two subtasks with a total cost of n-2 edges for the transaction schedule. Unfortunately, the problem of summing a subset is NP-hard.
Flow problem?
Perhaps this can also be converted into a min-cost flow problem. If you just want to simplify your initial schedule, you create a stream on it, the maximum capacity is the original amount of debits / credits. Debtors serve as an inflow (through a node connector that serves all debtors with capacity edges equal to their total debt), lenders are used as outflow nodes (with a similar node connector).
If you want to minimize the number of transactions, you will prefer to keep the "large" transactions and reduce the "small" ones. Therefore, the cost of each edge can be modeled as the inverse of the flow on that edge.