-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathGraph_Problem_42.java
More file actions
81 lines (71 loc) · 2.81 KB
/
Graph_Problem_42.java
File metadata and controls
81 lines (71 loc) · 2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package graphs;
/*
*
* Problem Title => Minimize Cash Flow among a given set of friends who have borrowed money from each other
* Difficulty Level : Hard
* Given a number of friends who have to give or take some amount of money from one another.
* Design an algorithm by which the total cash flow among all the friends is minimized.
*
* */
public class Graph_Problem_42 {
// Number of persons (or vertices in the graph)
static int N = 3;
// A utility function that returns index of minimum value in arr[]
static int getMin(int[] arr){
int minInd = 0;
for(int i = 1; i < N; i++)
if(arr[i] < arr[minInd])
minInd = i;
return minInd;
}
// A utility function that returns index of maximum value in arr[]
static int getMax(int[] arr){
int maxInd = 0;
for(int i = 1; i < N; i++)
if(arr[i] < arr[maxInd])
maxInd = i;
return maxInd;
}
// A utility function to return minimum of 2 values
static int minOf2(int x, int y){
return (x < y) ? x : y;
}
// amount[p] indicates the net amount to be credited/ debited to/from person 'p'.
// If amount[p] is positive, then i'th person will amount[i].
// If amount[p] is negative, them i'th person will give -amount[i]
static void minCashFlowRec(int[] amount){
int mxCredit = getMax(amount), mxDebit = getMin(amount);
// If both amounts are 0, then all amounts are settled
if(amount[mxCredit] == 0 && amount[mxDebit] == 0)
return;
// finding minimum of two amounts
int min = minOf2(-amount[mxDebit], amount[mxCredit]);
amount[mxCredit] -= min;
amount[mxDebit] += min;
System.out.println("Person " + mxDebit + " pays " + min + " to " + "Person " + mxCredit);
minCashFlowRec(amount);
}
// amount[p] indicates the net amount to be credited/debited to/from person 'p'.
// If amount[p] is positive, then i'th person will amount[i].
// If amount[p] is negative, then i'th person will give -amount[i].
static void minCashFlow(int[][] graph){
// Create an arrays.array amount[], initialize all value in it as 0.
int[] amount = new int[N];
// Calculate the net amount to be paid to person 'p', and stores it in amount[p].
// The value of amount[p] can be calculated by subtracting debts of 'p' from credits of 'p'.
for(int p = 0; p < N; p++){
for(int i = 0; i < N; i++)
amount[p] += (graph[i][p] - graph[p][i]);
}
minCashFlowRec(amount);
}
public static void main(String[] args) {
int[][] graph = {
{0, 1000, 2000},
{0, 0, 5000},
{0, 0, 0}
};
// here's the solution 😍
minCashFlow(graph);
}
}