Minimum cost to make an Array a permutation of first N natural numbers | Function to calculate minimum cost for making permutation of size N ; sorting the array in ascending order ; To store the required answer ; Traverse the whole array ; Return the required answer ; Driver code ; Function call
function make_permutation ( arr , n ) { arr . sort ( ) ; let ans = 0 ; for ( let i = 0 ; i < n ; i ++ ) ans += Math . abs ( i + 1 - arr [ i ] ) ; return ans ; } let arr = [ 5 , 3 , 8 , 1 , 1 ] ; let n = arr . length ; document . write ( make_permutation ( arr , n ) ) ;