Minimum cost to make an Array a permutation of first N natural numbers | C ++ program to calculate minimum cost to make an Array a permutation of first N natural numbers ; Function to calculate minimum cost for making permutation of size N ; sorting the array in ascending order ; To store the required answer ; Traverse the whole array ; Return the required answer ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int make_permutation ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) ans += abs ( i + 1 - arr [ i ] ) ; return ans ; } int main ( ) { int arr [ ] = { 5 , 3 , 8 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << make_permutation ( arr , n ) ; }