Minimum cost to make an Array a permutation of first N natural numbers
Last Updated :
05 Jul, 2022
Given an array arr of positive integers of size N, the task is to find the minimum cost to make this array a permutation of first N natural numbers, where the cost of incrementing or decrementing an element by 1 is 1.
Examples:
Input: arr[] = {1, 1, 7, 4}
Output: 5
Explanation:
Perform increment operation on 1 one time
Perform decrement operation on 7 four times
Resultant array = {1, 2, 3, 4}
Input: arr[] = {1, 2, 3, 4, 5}
Output: 0
Explanation:
The array is already a permutation.
Approach:
- Sort the array element in increasing order
- Traverse the sorted array:
- Check if the element at ith index (0 ? i < N) is equals to i + 1.
- If not, then make it equal and increment the difference between the two as the cost of this operation.
- When the traversal is complete, print the total cost of the operations performed.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
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);
}
|
Java
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));
}
}
|
Python3
def make_permutation(arr, n) :
arr.sort();
ans = 0 ;
for i in range (n) :
ans + = abs (i + 1 - arr[i]);
return ans;
if __name__ = = "__main__" :
arr = [ 5 , 3 , 8 , 1 , 1 ];
n = len (arr);
print (make_permutation(arr, n));
|
C#
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));
}
}
|
Javascript
<script>
function make_permutation(arr,n)
{
arr.sort();
let ans = 0;
for (let i = 0; i < n; i++)
ans += Math.abs(i + 1 - arr[i]);
return ans;
}
let arr = [ 5, 3, 8, 1, 1 ];
let n = arr.length;
document.write(make_permutation(arr, n));
</script>
|
Time Complexity: O(n*log(n))
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...