Given an array A[] of size N, the task is to find the minimum sum of numbers required to be added to array elements to convert the array into a permutation of 1 to N. If the array can not be converted to desired permutation, print -1.
Examples:
Input: A[] = {1, 1, 1, 1, 1}
Output: 10
Explanation: Increment A[1] by 1, A[2] by 2, A[3] by 3, A[4] by 4, thus A[] becomes {1, 2, 3, 4, 5}.
Minimum additions required = 1 + 2 + 3 + 4 = 10
Input: A[] = {2, 2, 3}
Output: -1
Approach: The idea is to use sorting. Follow these steps to solve this problem:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minimumAdditions( int a[], int n)
{
sort(a, a + n);
int ans = 0;
for ( int i = 0; i < n; i++) {
if ((i + 1) - a[i] < 0) {
return -1;
}
if ((i + 1) - a[i] > 0) {
ans += (i + 1 - a[i]);
}
}
return ans;
}
int main()
{
int A[] = { 1, 1, 1, 1, 1 };
int n = sizeof (A) / sizeof (A[0]);
cout << minimumAdditions(A, n);
return 0;
}
|
Java
import java.util.Arrays;
public class GFG {
static int minimumAdditions( int a[], int n)
{
Arrays.sort(a);
int ans = 0 ;
for ( int i = 0 ; i < n; i++) {
if ((i + 1 ) - a[i] < 0 ) {
return - 1 ;
}
if ((i + 1 ) - a[i] > 0 ) {
ans += (i + 1 - a[i]);
}
}
return ans;
}
public static void main(String[] args)
{
int A[] = { 1 , 1 , 1 , 1 , 1 };
int n = A.length;
System.out.println(minimumAdditions(A, n));
}
}
|
Python3
def minimumAdditions(a, n):
a = sorted (a)
ans = 0
for i in range (n):
if ((i + 1 ) - a[i] < 0 ):
return - 1
if ((i + 1 ) - a[i] > 0 ):
ans + = (i + 1 - a[i])
return ans
if __name__ = = '__main__' :
A = [ 1 , 1 , 1 , 1 , 1 ]
n = len (A)
print (minimumAdditions(A, n))
|
C#
using System;
class GFG{
static int minimumAdditions( int []a, int n)
{
Array.Sort(a);
int ans = 0;
for ( int i = 0; i < n; i++)
{
if ((i + 1) - a[i] < 0)
{
return -1;
}
if ((i + 1) - a[i] > 0)
{
ans += (i + 1 - a[i]);
}
}
return ans;
}
static void Main()
{
int [] A = { 1, 1, 1, 1, 1 };
int n = A.Length;
Console.Write(minimumAdditions(A, n));
}
}
|
Javascript
<script>
function minimumAdditions(a, n)
{
a.sort( function (a, b){ return a-b;});
let ans = 0;
for (let i = 0; i < n; i++) {
if ((i + 1) - a[i] < 0) {
return -1;
}
if ((i + 1) - a[i] > 0) {
ans += (i + 1 - a[i]);
}
}
return ans;
}
let A = [ 1, 1, 1, 1, 1 ];
let n = A.length;
document.write(minimumAdditions(A, n));
</script>
|
Time Complexity: O(N* log(N))
Auxiliary Space: O(1)