Longest remaining array of distinct elements possible after repeated removal of maximum and minimum elements of triplets | Java Program to implement the above approach ; Function to return length of longest remaining array of pairwise distinct array possible by removing triplets ; Stores the frequency of array elements ; Traverse the array ; Iterate through the map ; If frequency of current element is even ; Stores the required count of unique elements remaining ; If count is odd ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static int maxUniqueElements ( int [ ] Arr , int N ) { HashMap < Integer , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp . containsKey ( Arr [ i ] ) ) { mp . put ( Arr [ i ] , mp . get ( Arr [ i ] ) + 1 ) ; } else { mp . put ( Arr [ i ] , 1 ) ; } } int cnt = 0 ; for ( Map . Entry < Integer , Integer > entry : mp . entrySet ( ) ) { if ( ( entry . getValue ( ) ) % 2 == 0 ) { cnt ++ ; } } int ans = mp . size ( ) ; if ( cnt % 2 == 1 ) { ans -- ; } return ans ; } public static void main ( String [ ] args ) { int N = 5 ; int A [ ] = { 1 , 2 , 1 , 3 , 7 } ; System . out . println ( maxUniqueElements ( A , N ) ) ; } }