LC: 465. Optimal Account Balancing - spiralgo/algorithms GitHub Wiki
465. Optimal Account Balancing:
The Essence: This quote by Erdem, will make it clear to understand the intuition:
- If someone gives me
$10and I give that person$10back, it would mean that there are0 transactions needed. - If I give that person only
$8back, the situation is equivalent to me getting only$2from the person. - If someone comes and gives the person that
$2deficit, the situation is now equivalent to the new person giving me $2.
So, we calculate how much each person is in deficit/surplus. If their accounts are balanced with a $0 change, we don't include them in the debts list, as no transactions will be done with them. Some debts will directly cancel each other.
Details: You can find the detailed explanation and the implementations here: https://github.com/spiralgo/algorithms/pull/370