Maximum number of unique Triplets such that each element is selected only once | Function that finds maximum number of triplets with different elements ; Map M will store the frequency of each element in the array ; Priority queue of pairs { frequency , value } ; ans will store possible triplets ; Extract top 3 elements ; Make a triplet ; Decrease frequency and push back into priority queue if non - zero frequency ; Print the triplets ; Print the triplets ; Given array arr [ ] ; Function Call
function findTriplets ( ar , n ) { var mp = new Map ( ) ; for ( var x = 0 ; x < n ; x ++ ) { if ( mp . has ( ar [ x ] ) ) mp . set ( ar [ x ] , mp . get ( ar [ x ] ) + 1 ) else mp . set ( ar [ x ] , 1 ) } var pq = [ ] ; for ( var pa of mp ) pq . push ( [ pa [ 1 ] , pa [ 0 ] ] ) ; var ans = [ ] ; pq . sort ( ( a , b ) => { if ( a [ 0 ] == b [ 0 ] ) return a [ 1 ] - b [ 1 ] ; return a [ 0 ] - b [ 0 ] ; } ) ; while ( pq . length >= 3 ) { var ar = Array . from ( Array ( 3 ) , ( ) => Array ( 2 ) . fill ( 0 ) ) ; for ( var x = 0 ; x < 3 ; x ++ ) { ar [ x ] = pq [ pq . length - 1 ] ; pq . pop ( ) ; } ans . push ( [ ar [ 0 ] [ 1 ] , ar [ 1 ] [ 1 ] , ar [ 2 ] [ 1 ] ] ) ; for ( var x = 0 ; x < 3 ; x ++ ) { ar [ x ] [ 0 ] -- ; if ( ar [ x ] [ 0 ] ) pq . push ( ar [ x ] ) ; } pq . sort ( ( a , b ) => { if ( a [ 0 ] == b [ 0 ] ) return a [ 1 ] - b [ 1 ] ; return a [ 0 ] - b [ 0 ] ; } ) ; } document . write ( " " + " " ) ; document . write ( ans . length + " " ) ; for ( var pa of ans ) { for ( var v of pa ) document . write ( v + " " ) ; document . write ( " " ) ; } } var arr = [ 2 , 2 , 3 , 3 , 4 , 4 , 4 , 4 , 5 ] ; var n = arr . length ; findTriplets ( arr , n ) ;