Minimum deletions required such that any number X will occur exactly X times | Function to return the minimum deletions required ; To store the frequency of the array elements ; Store frequency of each element ; To store the minimum deletions required ; Value ; It 's frequency ; If number less than or equal to it 's frequency ; Delete extra occurrences ; Delete every occurrence of x ; Driver code
function MinDeletion ( a , n ) { let map = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( map [ a [ i ] ] ) map [ a [ i ] ] ++ ; else map [ a [ i ] ] = 1 } let ans = 0 ; for ( var m in map ) { let x = m ; let frequency = map [ m ] ; if ( x <= frequency ) { ans += ( frequency - x ) ; } else ans += frequency ; } ; return ans ; } let a = [ 2 , 3 , 2 , 3 , 4 , 4 , 4 , 4 , 5 ] ; let n = a . length ; document . write ( MinDeletion ( a , n ) ) ;