Approach
Depth-first search
For Optimal Account Balancing, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 39 lines of Java from the credited upstream file 465.java.
- The implementation visibly relies on sequence storage, ordered lookup.
- 4 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int minTransfers(int[][] transactions) {3 int[] balance = new int[21];4 List<Integer> debts = new ArrayList<>();5 6 for (int[] t : transactions) {7 final int from = t[0];8 final int to = t[1];9 final int amount = t[2];10 balance[from] -= amount;11 balance[to] += amount;12 }13 14 for (final int b : balance)15 if (b != 0)16 debts.add(b);17 18 return dfs(debts, 0);19 }20 21 private int dfs(List<Integer> debts, int s) {22 while (s < debts.size() && debts.get(s) == 0)23 ++s;24 if (s == debts.size())25 return 0;26 27 int ans = Integer.MAX_VALUE;28 29 for (int i = s + 1; i < debts.size(); ++i)30 if (debts.get(i) * debts.get(s) < 0) {31 debts.set(i, debts.get(i) + debts.get(s)); 32 ans = Math.min(ans, 1 + dfs(debts, s + 1));33 debts.set(i, debts.get(i) - debts.get(s)); 34 }35 36 return ans;37 }38}39