/* Groot has N trees lined up in front of him where the height of the i'th tree is denoted by H[i]. He wants to select some trees to replace his broken branches.
But he wants uniformity in his selection of trees. So he picks only those trees whose heights have frequency B. He then sums up the heights that occur B times.
(He adds the height only once to the sum and not B times).But the sum he ended up getting was huge so he prints it modulo 10^9+7.
In case no such cluster exists, Groot becomes sad and prints -1.
Constraints:
1<=N<=100000
1<=B<=N
0<=H[i]<=10^9 */
import java.util.*;
import java.lang.*;
import java.io.*;
// The main method must be in a class named "Main".
class Main {
public static int getsum(int N , int B , int C[]){
HashMap<Integer , Integer > fmap = new HashMap<>();
//Iterate over given array and count frequency of tree height in the array
for(int i=0 ; i< N ; i++){
int height = C[i];
fmap.put(height , fmap.getOrDefault(height,0)+ 1);
}
int sum=0;
boolean clus_e = false ; // Vbl : Cluster exists
//Iterate through frequency map and calculate sum of elements that occur B times in the array
for(int key : fmap.keySet()){
if(fmap.get(key) == B ){
sum += key ;
clus_e = true ;
}
}
// If not cluster exists , return -1
if(!clus_e){
return -1;
}
//Tale modulo 10^9+7
return sum% 1000000007;
}
public static void main(String[] args) {
int N = 5;
int B = 2 ;
int C[] = {1,2,2,3,3};
System.out.print(getsum(N,B,C));
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: