Maximum number of unique Triplets such that each element is selected only once | Java program for the above approach ; 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 ; Driver function ; Given array arr [ ] ; Function Call
import java . util . * ; import java . lang . * ; class GFG { static class pair { int first , second ; pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void findTriplets ( int arr [ ] , int n ) { Map < Integer , Integer > mp = new HashMap < > ( ) ; for ( int x = 0 ; x < n ; x ++ ) mp . put ( arr [ x ] , mp . getOrDefault ( arr [ x ] , 0 ) + 1 ) ; PriorityQueue < pair > pq = new PriorityQueue < > ( ( a , b ) -> a . first - b . first ) ; for ( Map . Entry < Integer , Integer > k : mp . entrySet ( ) ) pq . add ( new pair ( k . getValue ( ) , k . getKey ( ) ) ) ; ArrayList < List < Integer > > ans = new ArrayList < > ( ) ; while ( pq . size ( ) >= 3 ) { pair [ ] ar = new pair [ 3 ] ; for ( int x = 0 ; x < 3 ; x ++ ) { ar [ x ] = pq . peek ( ) ; pq . poll ( ) ; } ans . add ( Arrays . asList ( ar [ 0 ] . second , ar [ 1 ] . second , ar [ 2 ] . second ) ) ; for ( int x = 0 ; x < 3 ; x ++ ) { ar [ x ] . first -- ; if ( ar [ x ] . first != 0 ) pq . add ( ar [ x ] ) ; } } System . out . println ( " Maximum ▁ number ▁ of ▁ " + " possible ▁ triples : ▁ " + ans . size ( ) ) ; for ( List < Integer > pa : ans ) { for ( Integer v : pa ) System . out . print ( v + " ▁ " ) ; System . out . println ( ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 2 , 3 , 3 , 4 , 4 , 4 , 4 , 5 } ; int n = arr . length ; findTriplets ( arr , n ) ; } }