Length of array pair formed where one contains all distinct elements and other all same elements | Function to find the max size possible ; Counting the maximum frequency ; Counting total distinct elements ; Find max of both the answer ; Driver code
function findMaxSize ( a , n ) { var frq = Array ( n + 1 ) . fill ( 0 ) ; for ( var i = 0 ; i < n ; ++ i ) frq [ a [ i ] ] ++ ; var maxfrq = frq . reduce ( ( a , b ) => Math . max ( a , b ) ) var dist = n + 1 - frq . filter ( x => x == 0 ) . length ; var ans1 = Math . min ( maxfrq - 1 , dist ) ; var ans2 = Math . min ( maxfrq , dist - 1 ) ; var ans = Math . max ( ans1 , ans2 ) ; return ans ; } var arr = [ 4 , 2 , 4 , 1 , 4 , 3 , 4 ] ; var n = arr . length ; document . write ( findMaxSize ( arr , n ) ) ;