Rearrange array elements to maximize the sum of MEX of all prefix arrays | Java program for the above approach ; Function to find the maximum sum of MEX of prefix arrays for any arrangement of the given array ; Stores the final arrangement ; Sort the array in increasing order ; Iterate over the array arr [ ] ; Iterate over the array , arr [ ] and push the remaining occurrences of the elements into ans [ ] ; Print the array , ans [ ] ; Driver Code ; Given array ; Store the size of the array ; Function Call
import java . util . Arrays ; class GFG { static void maximumMex ( int arr [ ] , int N ) { int ans [ ] = new int [ 2 * N ] ; Arrays . sort ( ans ) ; int j = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( i == 0 arr [ i ] != arr [ i - 1 ] ) { j += 1 ; ans [ j ] = arr [ i ] ; } } for ( int i = 0 ; i < N ; i ++ ) { if ( i > 0 && arr [ i ] == arr [ i - 1 ] ) { j += 1 ; ans [ j ] = arr [ i ] ; } } for ( int i = 0 ; i < N ; i ++ ) System . out . print ( ans [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 0 , 0 } ; int N = arr . length ; maximumMex ( arr , N ) ; } }