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
< ? php function minimumMoves ( $ a , $ n ) { $ operations = 0 ; sort ( $ a ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ operations += abs ( $ a [ $ i ] - ( $ i + 1 ) ) ; return $ operations ; } $ arr = array ( 5 , 3 , 2 ) ; $ n = sizeof ( $ arr ) ; echo minimumMoves ( $ arr , $ n ) ; ? >