This is a hackerank easy question.
You are given a list of N people who are attending ACM-ICPC World Finals. Each of them are either well versed in a topic or they are not. Find out the maximum number of topics a 2-person team can know. And also find out how many teams can know that maximum number of topics.
Note Suppose a, b, and c are three different people, then (a,b) and (b,c) are counted as two different teams.
Input Format
The first line contains two integers, N and M, separated by a single space, where N represents the number of people, and M represents the number of topics. N lines follow. Each line contains a binary string of length M If the i'th line's j'th character is 1, then the i'th person knows the j'th topic; otherwise, he doesn't know the topic.
Constraints
2≤N≤500
1≤M≤500Output Format
On the first line, print the maximum number of topics a 2-person team can know. On the second line, print the number of 2-person teams that can know the maximum number of topics.
Here is what I wrote:
Scanner console = new Scanner(System.in);
int n = console.nextInt();
int m = console.nextInt();
console.nextLine();
String[] arr = new String[n];
for(int p=0; p<n; p++){
String s = console.nextLine();
arr[p] = s;
}
Map<Integer, List<List<Integer>>> counts = new HashMap<>();
for(int i = 0; i< n-1; i++){
String str=arr[i];
for(int j=i+1; j<n; j++){
String secondStr = arr[j];
int count = 0;
for(int k=0; k<m; k++){
if(str.charAt(k) == '1' || secondStr.charAt(k) == '1'){
count ++;
}
}
List<Integer> mapping = new ArrayList<>();
mapping.add(i+1);
mapping.add(j+1);
if(counts.containsKey(count)){
List<List<Integer>> existingMappings = counts.get(count);
existingMappings.add(mapping);
counts.put(count, existingMappings);
}else{
List<List<Integer>> newMappings = new ArrayList<>();
newMappings.add(mapping);
counts.put(count, newMappings);
}
}
}
int max = counts.keySet().stream().mapToInt(Integer::valueOf).max().orElse(0);
int occurences = counts.get(max).size();
System.out.println(max);
System.out.println(occurences);
This worked and passed the challenge. But it has a code smell: Too many loops and even inner loops. Any improvements?