Maximum number of pairs of distinct array elements possible by including each element in only one pair |  ; stores the frequency array ; maxi stores the maximum frequency of an element ; it stores the sum of all the frequency other than the element which has maximum frequency ; there will be always zero or more element which will not participate in making pairs ; if n is odd then except one element we can always form pair for every element if n is even then all the elements can form pair
let arr = [ 4 , 2 , 4 , 1 , 4 , 3 ] ; let n = arr . length ; let maxi = 0 , remain , ans ; let freq = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( freq . has ( arr [ i ] ) ) { freq . set ( arr [ i ] , freq . get ( arr [ i ] ) + 1 ) ; } else { freq . set ( arr [ i ] , 1 ) ; } } for ( let it of freq ) { maxi = Math . max ( maxi , it [ 1 ] ) ; } remain = n - maxi ; if ( maxi >= remain ) { ans = remain ; } else { ans = Math . floor ( n / 2 ) ; } document . write ( ans ) ; freq . clear ( ) ;