# Best way to clear balances between payers and payees

Say some 20 people go to a shop and everyone buys something. When it comes to paying, 5 of them pay the complete amount of 10,000\$ split unequally between them.

Since everyone bought different things they all owe different amounts to the payers. Now there are multiple ways the payers can clear the balances with the payees precisely 20 to the power 20.

My question is on what technical basis should the payers and payees contact each other for clearance? All the solutions can not be equally good, or are they?

One of the ways of clearing would be to find payers and payees with equal amount so that they can cancel out each other thus reducing the total number of transfers.

UPDATE:

1. People can transfer arbitrary amounts to anyone.
2. Minimizing total number of transfers is the main goal.
3. A payee can not pay an amount greater that what he owes and become secondary payer.
4. The output should be a list of suggested transfers. A suggested transfer would look like this `{FromUser: a, ToUser: b, ClearanceAmount: 100}`
5. The payers don't know who holds their debt.
6. The payees debt can be split across multiple payers.
7. The payees knows how much each payer paid from the total amount.
-
The question is not clear. Are you trying to optimize something here? Minimum number of transfers? Is there any limit to what people can pay each other (can they exchange arbitrary amounts of many with perfect precision)? – psr Mar 28 '13 at 17:47
Possible solution, if you just want to get the balance correct and are sure that all items were recorded accurately: create one account, let everyone pay into that account the amount his items are worth/retrieve the amount they paid to much. The account will have an amount of zero left, if everything was done correctly. If not, an error occured. If that does not solve it: the question is not clear, as mentionend by psr. – Thomas Mar 28 '13 at 17:50
@psr. I have updated the question with some more details. – Tushar Mathur Mar 28 '13 at 17:51
I think the question is still under-specified. Can the payers communicate with each other? Do they trust each other? Is there a cost to communication? Do you assume that all debtors (payees really isn't the right term) will pay what they owe? – Caleb Mar 28 '13 at 17:53
@Caleb, Payers CAN communicate, they do trust each other, no cost to communication and everyone pays what they owe. – Tushar Mathur Mar 28 '13 at 17:59