Minimum steps to convert an Array into permutation of numbers from 1 to N | C ++ program to find minimum number of steps to convert a given sequence into a permutation ; Function to find minimum number of steps to convert a given sequence into a permutation ; Sort the given array ; To store the required minimum number of operations ; Find the operations on each step ; Return the answer ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int get_permutation ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { result += abs ( arr [ i ] - ( i + 1 ) ) ; } return result ; } int main ( ) { int arr [ ] = { 0 , 2 , 3 , 4 , 1 , 6 , 8 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << get_permutation ( arr , n ) ; return 0 ; }