Count of permutations of an Array having maximum MEXs sum of prefix arrays | To calculate the factorial ; To return the number of permutations of an array with maximum MEXs sum of prefix array ; Map to store the frequency of each element ; Running a loop from i = 0 to i < n ; If continuity breaks , then break the loop ; Considering choices available to be filled at this position , i . e . mp [ i ] ; Decrement the count of remaining right elements ; Adding all permutations of the elements present to the right of the point where continuity breaks . ; Driver Code
function factorial ( n ) { let res = 1 , i ; for ( i = 2 ; i <= n ; i ++ ) { res *= i ; } return res ; } function countPermutations ( ar , n ) { let mp = new Map ( ) ; let ans = 1 , cnt = n ; for ( let i = 0 ; i < n ; i ++ ) { if ( mp . has ( ar [ i ] ) ) { mp . set ( ar [ i ] , mp . get ( ar [ i ] ) + 1 ) } else { mp . set ( ar [ i ] , 1 ) } } for ( let i = 0 ; i < n ; i ++ ) { if ( ! mp . has ( i ) ) { break ; } ans = ( ans * mp . get ( i ) ) ; cnt -- ; } ans = ans * factorial ( cnt ) ; return ans ; } let arr = [ 1 , 0 , 1 ] ; let N = arr . length document . write ( countPermutations ( arr , N ) ) ;