Minimum number of increment / decrement operations such that array contains all elements from 1 to N | Java implementation of the above approach ; Function to find the minimum operations ; Sort the given array ; Count operations by assigning a [ i ] = i + 1 ; Driver Code
import java . util . * ; class solution { static long minimumMoves ( int a [ ] , int n ) { long operations = 0 ; Arrays . sort ( a ) ; for ( int i = 0 ; i < n ; i ++ ) operations += ( long ) Math . abs ( a [ i ] - ( i + 1 ) ) ; return operations ; } public static void main ( String args [ ] ) { int arr [ ] = { 5 , 3 , 2 } ; int n = arr . length ; System . out . print ( minimumMoves ( arr , n ) ) ; } }