forked from adityabisoi/ds-algo-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.java
57 lines (46 loc) · 1.65 KB
/
solution.java
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
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
public class Solution {
public static void main(String args[]){
int[] parents = new int[30001];
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a, b;
while(n-->0){
a = sc.nextInt();
b = sc.nextInt();
if(parents[a] == 0) parents[a] = a;
if(parents[b] == 0) parents[b] = a;
//Disjoin set idea, keep updating the representative element of each set.
if(parents[a] != 0 || parents[b] != 0){
int low = Math.min(parents[a], parents[b]);
int high = Math.max(parents[a], parents[b]);
for(int i=0; i<parents.length; i++){
if(parents[i] == high)
//let representative always be the smallest in the set
parents[i] = low;
}
}
}
//convert int[] to Integer[] in order to use Collections.frequency(Integer[], int)
Integer[] newArray = new Integer[parents.length];
int i = 0;
for (int value : parents) {
newArray[i++] = value;
}
List<Integer> ints = Arrays.asList(newArray);
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(int item : newArray) {
if(item != 0) {
int frequency = Collections.frequency(ints, item);
min = Math.min(min, frequency);
max = Math.max(max, frequency);
}
}
System.out.println(min + " " + max);
}
}