Rearrange array elements to maximize the sum of MEX of all prefix arrays | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maximumMex ( int arr [ ] , int N ) { vector < int > ans ; sort ( arr , arr + N ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( i == 0 arr [ i ] != arr [ i - 1 ] ) ans . push_back ( arr [ i ] ) ; } for ( int i = 0 ; i < N ; i ++ ) { if ( i > 0 && arr [ i ] == arr [ i - 1 ] ) ans . push_back ( arr [ i ] ) ; } for ( int i = 0 ; i < N ; i ++ ) cout << ans [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 1 , 0 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maximumMex ( arr , N ) ; return 0 ; }