Maximum number of pairs of distinct array elements possible by including each element in only one pair | package whatever do not write package name here ; Function to count the maximum number of pairs having different element from the given array ; Stores the frequency of array element ; Stores maximum count of pairs ; Increasing the frequency of every element ; Stores the frequencies of array element from highest to lowest ; Pushing the frequencies to the priority queue ; Iterate until size of PQ > 1 ; Stores the top two element ; Form the pair between the top two pairs ; Decrement the frequencies ; Insert updated frequencies if it is greater than 0 ; Return the total count of resultant pairs ; Driver Code
import java . io . * ; import java . util . * ; class GFG { public static int maximumPairs ( int [ ] a , int n ) { HashMap < Integer , Integer > freq = new HashMap < Integer , Integer > ( ) ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int c = a [ i ] ; if ( freq . containsKey ( c ) ) { freq . put ( c , freq . get ( c ) + 1 ) ; } else { freq . put ( c , 1 ) ; } } PriorityQueue < Integer > pq = new PriorityQueue < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( freq . containsKey ( a [ i ] ) ) { pq . add ( freq . get ( a [ i ] ) ) ; freq . remove ( a [ i ] ) ; } } while ( pq . size ( ) > 1 ) { int freq1 = pq . poll ( ) ; int freq2 = pq . poll ( ) ; count ++ ; freq1 -- ; freq2 -- ; if ( freq1 > 0 ) pq . add ( freq1 ) ; if ( freq2 > 0 ) pq . add ( freq2 ) ; } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 2 , 4 , 1 , 4 , 3 } ; int N = 6 ; System . out . println ( maximumPairs ( arr , N ) ) ; } }