Minimum number of increment / decrement operations such that array contains all elements from 1 to N | Function to find the minimum operations ; Sort the given array ; Count operations by assigning a [ i ] = i + 1 ; Driver code
function minimumMoves ( a , n ) { let operations = 0 ; a . sort ( ) ; for ( let i = 0 ; i < n ; i ++ ) operations += Math . abs ( a [ i ] - ( i + 1 ) ) ; return operations ; } let arr = [ 5 , 3 , 2 ] ; let n = arr . length ; document . write ( minimumMoves ( arr , n ) ) ;