Staff

Optimal Account Balancing

You are given an array transactions where transactions[i] = [from_i, to_i, amount_i] indicates that person from_i gave person to_i amount_i dollars.

After all transactions, each person may have a net balance: they may be owed money, owe money, or be settled. Your task is to determine the minimum number of additional transactions required so that every person's net balance becomes zero.

Return the minimum number of transactions needed to settle all debts.

Example 1
Inputtransactions = [[0,1,10],[2,0,5]]
Output2
Person 1 must repay 5 dollars to person 0 and 5 dollars to person 2, requiring 2 transactions.
Example 2
Inputtransactions = [[0,1,10],[1,0,1],[1,2,5],[2,0,5]]
Output1
After netting all balances, only person 1 owes person 0 4 dollars, so 1 transaction is enough.

Constraints

  • 1 <= transactions.length <= 8
  • transactions[i].length == 3
  • 0 <= from_i, to_i < 12
  • from_i != to_i
  • 1 <= amount_i <= 100

Asked at 11 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate