


A group of friends went on a trip and sometimes lent each other money. Each transaction among them is represented by the tuple (X, Y, Z) which means person ‘X’ gave person ‘Y’ $Z. Given a list of ‘N’ transactions between a group of friends, return the minimum number of transactions required to settle the debt.
Example:
Alice paid for Bill's lunch for $10. Then later Chris gave Alice $5 for a taxi ride. Assuming Alice, Bill, and Chris are person 0, 1, and 2 respectively (0, 1, 2 are the person's ID), the transaction can be represented as [[0, 1, 10], [2, 0, 5]].So here the minimum number of transactions to settle the debt is 2.
The first line of input contains an integer ‘T’ denoting the number of test cases.
The first line of every test case contains one integer ‘N’ where ‘N’ denotes the number of transactions between a group of friends.
Then N lines contain three space-separated integers ‘X’, ‘Y’ and ‘Z’ which denotes person X gave person Y $Z in the form of N x 3 ‘ARR’ matrix where the first column represents lender, the second column represents receiver and the last column represents the money given.
Output format:
For each test case, print a single line containing a single integer denoting the minimum number of transactions required to settle the debt.
The output for each test case will be printed on a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
A transaction will be given as a tuple (x, y, z). Note that x ≠ y and z > 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.
1 <= T <= 10
1 <= N <= 9
Where ‘T’ represents the number of test cases, and ‘N’ represents the number of transactions among the friends.
Time Limit: 1 sec.
1
2
0 1 10
2 0 5
2
For the first test case,
Person-0 gave person-1 $10.
Person-2 gave person-0 $5.
Therefore, Two transactions are needed. One way to settle the debt is person-1 pays person-0 and person-2 $5 each.
1
4
0 1 10
1 0 1
1 2 5
2 0 5
1
For the first test case,
Person-0 gave person-1 $10.
Person-1 gave person-0 $1.
Person-1 gave person-2 $5.
Person-2 gave person-0 $5.
Therefore, only 1 transaction is needed. Person-1 only needs to give person-0 $4, and all debt is settled.
Think of a recursive solution.
Approach:
Algorithm:
O(N!), where N is the number of transactions.
Storing the initial debts of each person on the map will take O(N) time. Now traversing the map and storing all non-zero values in an array will take O(N) time. Calling the recursive function N times and performing backtracking along with it will take O(N!) time. Thus, the total time complexity will be O(N + N + N!) = O(N!).
O(N), where ‘N’ is the number of Transactions
O(N) extra space is required for the Hashmap. Also, O(N) extra space is required to build the temporary array. Hence, the overall space complexity is O(N).