Skip to main content

Optimal Account Balancing

HardPremium

A group of friends lent each other money. Each entry in transactions is [giver, receiver, amount]: the person with id giver gave amount dollars to the person with id receiver.

Return the fewest transfers needed to settle every debt, so that everyone ends up even.

Example 1

Input: transactions = [[0, 1, 10], [2, 0, 5]] Output: 2

Person 0 gave 10 and received 5, so they're owed 5. Person 1 owes 10 and person 2 is owed 5. Person 1 can pay 5 to person 0 and 5 to person 2: two transfers.

Example 2

Input: transactions = [[0, 1, 10], [1, 0, 1], [1, 2, 5], [2, 0, 5]] Output: 1

Person 0 is owed 4, person 1 owes 4 and person 2 is even. One transfer of 4 from person 1 to person 0 settles everything.

Constraints

  • 1 <= transactions.length <= 8
  • 0 <= giver, receiver < 12, and giver != receiver
  • 1 <= amount <= 100