Maximum number of pairs of distinct array elements possible by including each element in only one pair | 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 ; 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
function maximumPairs ( a , n ) { var freq = new Map ( ) ; var count = 0 ; for ( var i = 0 ; i < n ; ++ i ) { if ( freq . has ( a [ i ] ) ) freq . set ( a [ i ] , freq . get ( a [ i ] ) + 1 ) else freq . set ( a [ i ] , 1 ) } var pq = [ ... freq . values ( ) ] ; pq . sort ( ( a , b ) => a - b ) ; while ( pq . length > 1 ) { var freq1 = pq [ pq . length - 1 ] ; pq . pop ( ) ; var freq2 = pq [ pq . length - 1 ] ; pq . pop ( ) ; count ++ ; freq1 -- ; freq2 -- ; if ( freq1 > 0 ) pq . push ( freq1 ) ; if ( freq2 > 0 ) pq . push ( freq2 ) ; pq . sort ( ( a , b ) => a - b ) ; } return count ; } var arr = [ 4 , 2 , 4 , 1 , 4 , 3 ] ; var N = arr . length ; document . write ( maximumPairs ( arr , N ) ) ;