Untitled
unknown
plain_text
a year ago
1.5 kB
11
Indexable
/*package whatever //do not write package name here */ import java.io.; import java.util.; class Count{ int element; int count; public Count(int element,int count){ this.count=count; this.element=element; } } // class CountComparator implements Comparator { // @Override // public int compare(Count c1, Count c2) { // return Integer.compare(c1.count, c2.count); // } // } class GFG { public static void main (String[] args) { int arr[]= {3, 3, 1, 2,4,5}; int n=5; System.out.println(solve(n,arr)); } public static int solve(int n,int arr[]){ HashMap<Integer,Integer> hm = new HashMap<>(); for(int i:arr){ if(hm.containsKey(i)){ hm.put(i,hm.get(i)+1); } else{ hm.put(i,1); } } PriorityQueue maxHeap = new PriorityQueue<>((count1, count2) -> Integer.compare(count2.count, count1.count)); for (Map.Entry<Integer,Integer> mapElement : hm.entrySet()) { int key = mapElement.getKey(); // Adding some bonus marks to all the students int value = (mapElement.getValue()); maxHeap.add(new Count(key,value)); } while(!maxHeap.isEmpty()&&maxHeap.size()>1){ Count ele1=maxHeap.poll(); Count ele2=maxHeap.poll(); if(ele1.count>1){ ele1.count=ele1.count-1; maxHeap.add(ele1); } if(ele1.count>1){ ele2.count=ele2.count-1; maxHeap.add(ele2); } } int ans = 0; while(!maxHeap.isEmpty()){ ans+=maxHeap.poll().count; } return ans; }
Editor is loading...
Leave a Comment