Minimum cost to make an Array a permutation of first N natural numbers | Java 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
import java . util . * ; class GFG { static int make_permutation ( int arr [ ] , int n ) { Arrays . 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 ; System . out . print ( make_permutation ( arr , n ) ) ; } }