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
using System ; class GFG { static int make_permutation ( int [ ] arr , int n ) { Array . Sort ( arr ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) ans += Math . Abs ( i + 1 - arr [ i ] ) ; return ans ; } public static void Main ( string [ ] args ) { int [ ] arr = { 5 , 3 , 8 , 1 , 1 } ; int n = arr . Length ; Console . WriteLine ( make_permutation ( arr , n ) ) ; } }