Given an array of N elements, the task is to convert it into a permutation (Each number from 1 to N occurs exactly once) by using the following operations a minimum number of times:
- Increment any number.
- Decrement any number.
Examples:
Input: arr[] = {1, 1, 4}
Output: 2
The array can be converted into [1, 2, 3]
by adding 1 to the 1st index i.e. 1 + 1 = 2
and decrementing 2nd index by 1 i.e. 4- 1 = 3
Input: arr[] = {3, 0}
Output: 2
The array can be converted into [2, 1]
Approach: To minimize the number of moves/operations, sort the given array and make a[i] = i+1 (0-based) which will take abs(i+1-a[i]) no. of operations for each element.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
long long minimumMoves( int a[], int n)
{
long long operations = 0;
sort(a, a + n);
for ( int i = 0; i < n; i++)
operations += abs (a[i] - (i + 1));
return operations;
}
int main()
{
int arr[] = { 5, 3, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << minimumMoves(arr, n);
return 0;
}
|
Java
import java.util.*;
class solution
{
static long minimumMoves( int a[], int n)
{
long operations = 0 ;
Arrays.sort(a);
for ( int i = 0 ; i < n; i++)
operations += ( long )Math.abs(a[i] - (i + 1 ));
return operations;
}
public static void main(String args[])
{
int arr[] = { 5 , 3 , 2 };
int n = arr.length;
System.out.print(minimumMoves(arr, n));
}
}
|
Python3
def minimumMoves(a, n):
operations = 0
a.sort(reverse = False )
for i in range ( 0 ,n, 1 ):
operations = operations + abs (a[i] - (i + 1 ))
return operations
if __name__ = = '__main__' :
arr = [ 5 , 3 , 2 ]
n = len (arr)
print (minimumMoves(arr, n))
|
C#
using System;
class GFG
{
static long minimumMoves( int []a, int n)
{
long operations = 0;
Array.Sort(a);
for ( int i = 0; i < n; i++)
operations += ( long )Math.Abs(a[i] - (i + 1));
return operations;
}
static public void Main ()
{
int []arr = { 5, 3, 2 };
int n = arr.Length;
Console.WriteLine(minimumMoves(arr, n));
}
}
|
PHP
<?php
function minimumMoves( $a , $n )
{
$operations = 0;
sort( $a );
for ( $i = 0; $i < $n ; $i ++)
$operations += abs ( $a [ $i ] -
( $i + 1));
return $operations ;
}
$arr = array ( 5, 3, 2 );
$n = sizeof( $arr );
echo minimumMoves( $arr , $n );
?>
|
Javascript
<script>
function minimumMoves(a, n)
{
let operations = 0;
a.sort();
for (let i = 0; i < n; i++)
operations += Math.abs(a[i] - (i + 1));
return operations;
}
let arr = [ 5, 3, 2 ];
let n = arr.length;
document.write(minimumMoves(arr, n));
</script>
|
Complexity Analysis:
- Time Complexity: O(NlogN)
- Auxiliary Space: O(1)