465 Optimal Account Balancing
1. Question
A group of friends went on holiday and sometimes lent each other money. For example, Alice paid for Bill's lunch for $10. Then later Chris gave Alice $5 for a taxi ride. We can model each transaction as a tuple (x, y, z) which means person x gave person y $z. Assuming Alice, Bill, and Chris are person 0, 1, and 2 respectively (0, 1, 2 are the person's ID), the transactions can be represented as[[0, 1, 10], [2, 0, 5]].
Given a list of transactions between a group of people, return the minimum number of transactions required to settle the debt.
Note:
A transaction will be given as a tuple (x, y, z). Note that
x ≠ yandz > 0.Person's IDs may not be linear, e.g. we could have the persons 0, 1, 2 or we could also have the persons 0, 2, 6.
Example 1:
Input: [[0,1,10], [2,0,5]]
Output: 2
Explanation:
Person #0 gave person #1 $10.
Person #2 gave person #0 $5.
Two transactions are needed. One way to settle the debt is person #1 pays person #0 and #2 $5 each.Example 2:
2. Implementation
(1) Hash Table + Backtracking
思路:
(1)用hashmap预处理transaction,将balance为0的人去除掉
(2)用backtracking对枚举出所有能将剩余debt settle的组合,
(2) HashMap + Two Pointers + Backtracking
思路: 这里和上面解法唯一的不同的是在第二步里,我们进行进一步的预处理,用two pointers的方法去除掉可以直接match的debt
3. Time & Space Complexity
(1) Hash Table + Backtracking: 时间复杂度O(n!), n是debt不为0的个数,空间复杂度O(m + n), m是人的个数
(2) HashMap + Two Pointers + Backtracking:时间复杂度O(n!), 空间复杂度O(m + n)
Last updated
Was this helpful?