Minimum number of increment / decrement operations such that array contains all elements from 1 to N | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long minimumMoves ( int a [ ] , int n ) { long long operations = 0 ; sort ( a , a + n ) ; for ( int i = 0 ; i < n ; i ++ ) operations += abs ( a [ i ] - ( i + 1 ) ) ; return operations ; } int main ( ) { int arr [ ] = { 5 , 3 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimumMoves ( arr , n ) ; return 0 ; }