1
+ class Solution {
2
+ public double maxAmount (String initCurr , List <List <String >> pairs1 , double [] rates1 , List <List <String >> pairs2 , double [] rates2 ) {
3
+ // adj list
4
+ HashMap <String , HashMap <String ,Double >> adj = new HashMap <>();
5
+
6
+ for (int i =0 ;i <pairs1 .size ();i ++){
7
+ String a = pairs1 .get (i ).get (0 );
8
+ String b = pairs1 .get (i ).get (1 );
9
+ double rate = rates1 [i ];
10
+
11
+ adj .putIfAbsent (a ,new HashMap <>());
12
+ adj .putIfAbsent (b ,new HashMap <>());
13
+
14
+ adj .get (a ).put (b ,Math .max (adj .get (a ).getOrDefault (b ,0.0 ),rate ));
15
+ adj .get (b ).put (a ,Math .max (adj .get (b ).getOrDefault (a ,0.0 ),1 /rate ));
16
+
17
+ }
18
+ //System.out.println(adj);
19
+
20
+ HashMap <String ,Double > state = new HashMap <>();
21
+
22
+ dfs1 (initCurr , "" , 1.0 , adj , state );
23
+
24
+ System .out .println (state );
25
+
26
+ adj = new HashMap <>();
27
+ for (int i =0 ;i <pairs2 .size ();i ++){
28
+ String a = pairs2 .get (i ).get (0 );
29
+ String b = pairs2 .get (i ).get (1 );
30
+ double rate = rates2 [i ];
31
+
32
+ adj .putIfAbsent (a ,new HashMap <>());
33
+ adj .putIfAbsent (b ,new HashMap <>());
34
+
35
+ adj .get (a ).put (b ,Math .max (adj .get (a ).getOrDefault (b ,0.0 ),rate ));
36
+ adj .get (b ).put (a ,Math .max (adj .get (b ).getOrDefault (a ,0.0 ),1 /rate ));
37
+
38
+ }
39
+
40
+ //System.out.println(adj);
41
+
42
+ double [] res = {1.0 };
43
+
44
+ for (Map .Entry <String , Double > entry : state .entrySet ()) {
45
+ dfs2 (entry .getKey (), "" , entry .getValue (), adj , initCurr , res );
46
+ }
47
+
48
+ return res [0 ];
49
+ }
50
+
51
+
52
+ public void dfs1 (String curr , String prev ,double val , HashMap <String ,HashMap <String ,Double >> adj ,
53
+ HashMap <String ,Double > state ){
54
+ state .put (curr , Math .max (state .getOrDefault (curr , 0.0 ),val ));
55
+
56
+ for (Map .Entry <String , Double > adjNode : adj .getOrDefault (curr , new HashMap <>()).entrySet ()){
57
+
58
+ String nextCurr = adjNode .getKey ();
59
+ double exRate = adjNode .getValue ();
60
+
61
+ if (!nextCurr .equals (prev )){
62
+ dfs1 (nextCurr , curr , val *exRate , adj , state );
63
+ }
64
+ }
65
+ }
66
+
67
+ public void dfs2 (String curr , String prev , double val ,HashMap <String ,HashMap <String ,Double >> adj ,
68
+ String initCurr ,double [] res ){
69
+ if (curr .equals (initCurr )){
70
+ res [0 ] = Math .max (res [0 ],val );
71
+ }
72
+ for (Map .Entry <String , Double > adjNode : adj .getOrDefault (curr , new HashMap <>()).entrySet ()){
73
+
74
+ String nextCurr = adjNode .getKey ();
75
+ double exrate = adjNode .getValue ();
76
+
77
+ if (!nextCurr .equals (prev )){
78
+ dfs2 (nextCurr ,curr ,val *exrate ,adj ,initCurr ,res );
79
+ }
80
+ }
81
+ }
82
+ }
0 commit comments