Ctrl K

Settle Up in the Fewest Transfers

Hard
A group of friends has been lending each other money. Each record payments[i] = [from, to, amount] means person from gave person to the sum amount, so to now owes it back. Everyone wants to settle up. A transfer is any sum sent from one person to another, and you may send money to anyone, not only to the person you borrowed from. Return the smallest number of transfers after which nobody owes anybody anything.
Example 1
payments=[[0, 1, 20], [1, 2, 20]] → 1

Person 1 received 20 and passed on 20, so they are even. Person 2 just pays 20 back to person 0: one transfer.

Example 2
payments=[[0, 1, 5], [1, 0, 5]] → 0

The debts cancel out, so no transfers are needed.

Example 3
payments=[[0, 1, 10], [0, 2, 10], [3, 0, 15]] → 3

Net result: 1 and 2 owe 10 each, 0 is owed 5 and 3 is owed 15. No smaller group balances on its own, so 3 transfers are needed, e.g. 1→3 for 10, 2→3 for 5 and 2→0 for 5.

Constraints
  • 1 ≤ len(payments) ≤ 8
  • payments[i] = [from, to, amount]
  • 0 ≤ from, to < 12, from ≠ to
  • 1 ≤ amount ≤ 100
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSquare-Sum Chains HardBest Word Set From Tiles HardOrders of Identical Parts HardSharing Jobs Fairly HardSquare Frame From Sticks Medium
loading Python…
Input
payments=[[0, 1, 20], [1, 2, 20]]
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 66 tests on the server, hidden ones included.