Problem · Array

Optimal Account Balancing

Learn this problem
HardSalesforce logoSalesforceFULLTIMEPHONE SCREEN
See Salesforce hiring insights

Problem statement

You are given an array transactions, where each row [from, to, amount] means that the person with identifier from gave amount units of money to the person with identifier to.

After all listed transactions, people may make additional transfers between any pair of accounts to settle every net balance.

Return the minimum number of additional transfers required so that every person's final net balance is zero.

Function

minTransfers(transactions: int[][]) → int

Examples

Example 1

transactions = [[0,1,10],[2,0,5]]return = 2

Person 0 must receive a net amount of 5, person 1 must receive 10, and person 2 must pay 5. At least two non-zero accounts must receive money, and two transfers are sufficient.

Example 2

transactions = [[0,1,10],[1,0,1],[1,2,5],[2,0,5]]return = 1

The final balances can be settled with one transfer of 4 from person 1 to person 0.

Example 3

transactions = [[0,1,10],[1,2,10],[2,0,10]]return = 0

Every person's incoming and outgoing amounts already cancel, so no additional transfer is needed.

Constraints

  • 1 <= transactions.length <= 8.
  • transactions[i].length == 3.
  • 0 <= from, to < 12.
  • from != to.
  • 1 <= amount <= 100.

More Salesforce problems

drafts saved locally
public int minTransfers(int[][] transactions) {
    // Write your code here.
}
transactions[[0,1,10],[2,0,5]]
expected2
checking account