-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathg.java
More file actions
executable file
·106 lines (93 loc) · 3.25 KB
/
g.java
File metadata and controls
executable file
·106 lines (93 loc) · 3.25 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Neel_Kapadia
*/
import java.util.*;
public class g {
int[] A;
int[] E;
HashMap<Integer, List<Integer>> hashMap = new HashMap<Integer, List<Integer>>();
HashSet<Integer> hashSet = new HashSet<Integer>();
public int LongestPathWithSameValue(int[] A, int[] E) {
// write your code in Java SE 8
this.A = A;
this.E = E;
int i = 0;
while (i < E.length) {
List<Integer> list;
int node1 = E[i++];
int node2 = E[i++];
list = hashMap.getOrDefault(node1, new ArrayList<Integer>());
if (!list.contains(node2)) {
list.add(node2);
hashMap.put(node1, list);
}
list = hashMap.getOrDefault(node2, new ArrayList<Integer>());
if (!list.contains(node1)) {
list.add(node1);
hashMap.put(node2, list);
}
}
// graph adjacency list created
int len = 0;
Iterator iterator = hashMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry pair = (Map.Entry) iterator.next();
int parent = (int) pair.getKey();
hashSet.add(parent);
List<Integer> list = (List<Integer>) pair.getValue();
int secondMax = 0;
int maximum = 0;
for (i = 0; i < list.size(); i++) {
if (!hashSet.contains(list.get(i))) {
int val = getDFSLength(list.get(i), A[parent - 1]);
if (val > secondMax) {
secondMax = val;
}
if (val > maximum) {
secondMax = maximum;
maximum = val;
}
}
}
len = Math.max(len, maximum + secondMax);
hashSet.remove(parent);
}
return len;
}
public int getDFSLength(int selfNode, int parentVal) {
hashSet.add(selfNode);
if (A[selfNode - 1] == parentVal) {
int sum = 1;
if (hashMap.containsKey(selfNode)) {
List<Integer> list = hashMap.get(selfNode);
for (int i = 0; i < list.size(); i++) {
if (!hashSet.contains(list.get(i))) {
sum = Math.max(sum, 1 + getDFSLength(list.get(i), A[selfNode - 1]));
}
}
hashSet.remove(selfNode);
return sum;
} else {
hashSet.remove(selfNode);
return 1;
}
} else {
hashSet.remove(selfNode);
return 0;
}
}
public static void main(String[] args) {
g g1 = new g();
int A[] = {1, 1, 1, 1, 2};
int E[] = {1, 2, 1, 3, 2, 4, 2, 5};
// [1, 1, 1, 2, 2], [1, 2, 1, 3, 2, 4, 2, 5]
int len = g1.LongestPathWithSameValue(A, E);
System.out.println(len);
}
}