Optimal Account Balancing - Problem
You are given an array of transactions transactions where transactions[i] = [fromi, toi, amounti] indicates that the person with ID = fromi gave amounti $ to the person with ID = toi.
Return the minimum number of transactions required to settle the debt.
A debt is settled when the net balance of each person becomes zero. Multiple transactions between the same people are allowed.
Input & Output
Example 1 — Basic Three Person Settlement
$
Input:
transactions = [[0,1,10],[2,0,5]]
›
Output:
2
💡 Note:
Person 0 gave $10 to person 1 and received $5 from person 2. Net balances: Person 0: -$5, Person 1: +$10, Person 2: -$5. Person 1 pays $5 to person 0, and person 1 pays $5 to person 2. Minimum 2 transactions needed.
Example 2 — Already Settled
$
Input:
transactions = [[0,1,10],[1,0,1],[1,2,5],[2,0,5]]
›
Output:
1
💡 Note:
Net balances: Person 0: -$5, Person 1: +$4, Person 2: $0, Person 0 (unnamed): +$1. After calculating all balances, only 1 transaction needed to settle remaining debts.
Example 3 — No Settlements Needed
$
Input:
transactions = [[0,1,5],[1,2,5],[2,0,5]]
›
Output:
0
💡 Note:
This forms a cycle: person 0 → person 1 → person 2 → person 0. All net balances are zero, so no additional transactions needed.
Constraints
- 1 ≤ transactions.length ≤ 8
- transactions[i].length == 3
- 0 ≤ fromi, toi < 12
- fromi ≠ toi
- 1 ≤ amounti ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Initial Transactions
People make payments to each other
2
Calculate Net Balances
Determine who owes money and who is owed
3
Optimal Settlement
Find minimum transactions to settle all debts
Key Takeaway
🎯 Key Insight: Only people with non-zero balances need to make settlement transactions
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code