Winner Of An Election Geeks For Geeks
class Solution
{
//Function to return the name of candidate that received maximum votes.
public static String[] winner(String arr[], int n)
{
TreeMap<String,Integer> map=new TreeMap<String,Integer>();
for(int i=0;i<arr.length;i++){
if(map.containsKey(arr[i])){
map.put(arr[i],map.get(arr[i])+1);
}
else
map.put(arr[i],1);
}
PriorityQueue<Integer> pq=new PriorityQueue<Integer>();
int a=0;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
a=entry.getValue();
if(pq.isEmpty()){
pq.add(a);
}
else{
if(pq.peek()<a){
pq.remove();
pq.add(a);
}
}
}
String arr2[]=new String[2];
for (Map.Entry<String, Integer> entry1 : map.entrySet()) {
int a1=entry1.getValue();
if(a1==pq.peek()){
arr2[0]=entry1.getKey();
arr2[1]=String.valueOf(a1);
break;
}
}
return arr2;
}
}
Comments
Post a Comment