Minimize swaps required to maximize the count of elements replacing a greater element in an Array
Last Updated :
15 Apr, 2023
Given an array A[], consisting of N elements, the task is to find the minimum number of swaps required such that array elements swapped to replace a higher element, in the original array, are maximized.
Examples:
Input: A[] = {4, 3, 3, 2, 5}
Output: 3
Explanation:
Swap 1: {4, 3, 3, 2, 5} -> {5, 3, 3, 2, 4}
Swap 2: {5, 3, 3, 2, 4} -> {3, 3, 5, 2, 4}
Swap 3: {3, 3, 5, 2, 4} -> {3, 3, 2, 5, 4}
Therefore, elements {4, 3, 2} occupies original position of a higher element after swapping
Input:. A[] = {6, 5, 4, 3, 2, 1}
Output: 5
Naive Approach: The simplest approach to solve the problem can be implemented as follows:
- Sort the array in ascending order.
- Initialize two variables, result, and index, to store the count and the index up to which it has been considered in the original array, respectively.
- Iterate over the array elements. For any element A[i], go to a value in the array which is greater than ai and increment the index variable accordingly.
- After finding an element greater than A[i], increment result, and index.
- If the index has reached the end of the array, no elements are left to be swapped with previously checked elements.
- Therefore, print count.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countSwaps( int A[], int n)
{
sort(A, A + n);
int ind = 1, res = 0;
for ( int i = 0; i < n; i++) {
while (ind < n and A[ind] == A[i])
ind++;
if (ind < n and A[ind] > A[i]) {
res++;
ind++;
}
if (ind >= n)
break ;
}
return res;
}
int main()
{
int A[] = { 4, 3, 3, 2, 5 };
cout << countSwaps(A, 5);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int countSwaps( int A[], int n)
{
Arrays.sort(A);
int ind = 1 , res = 0 ;
for ( int i = 0 ; i < n; i++)
{
while (ind < n && A[ind] == A[i])
ind++;
if (ind < n && A[ind] > A[i])
{
res++;
ind++;
}
if (ind >= n)
break ;
}
return res;
}
public static void main(String[] args)
{
int A[] = { 4 , 3 , 3 , 2 , 5 };
System.out.print(countSwaps(A, 5 ));
}
}
|
Python3
def countSwaps(A, n):
A.sort()
ind, res = 1 , 0
for i in range (n):
while (ind < n and A[ind] = = A[i]):
ind + = 1
if (ind < n and A[ind] > A[i]):
res + = 1
ind + = 1
if (ind > = n):
break
return res
A = [ 4 , 3 , 3 , 2 , 5 ]
print (countSwaps(A, 5 ))
|
C#
using System;
class GFG{
static int countSwaps( int []A, int n)
{
Array.Sort(A);
int ind = 1, res = 0;
for ( int i = 0; i < n; i++)
{
while (ind < n && A[ind] == A[i])
ind++;
if (ind < n && A[ind] > A[i])
{
res++;
ind++;
}
if (ind >= n)
break ;
}
return res;
}
public static void Main(String[] args)
{
int []A = { 4, 3, 3, 2, 5 };
Console.Write(countSwaps(A, 5));
}
}
|
Javascript
<script>
function countSwaps(A, n)
{
A.sort();
let ind = 1, res = 0;
for (let i = 0; i < n; i++)
{
while (ind < n && A[ind] == A[i])
ind++;
if (ind < n && A[ind] > A[i])
{
res++;
ind++;
}
if (ind >= n)
break ;
}
return res;
}
let A = [ 4, 3, 3, 2, 5 ];
document.write(countSwaps(A, 5));
</script>
|
Time Complexity: O(N * log N)
Auxiliary Space: O(1)
Efficient Approach:
Since any swap between two unequal elements leads to an element replacing a higher element, it can be observed that the minimum number of swaps required is N – (the maximum frequency of an array element). Therefore, find the most frequent element in the array using HashMap, and print the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countSwaps( int A[], int n)
{
map< int , int > mp;
int max_frequency = 0;
for ( int i = 0; i < n; i++) {
mp[A[i]]++;
max_frequency
= max(max_frequency, mp[A[i]]);
}
return n - max_frequency;
}
int main()
{
int A[] = { 6, 5, 4, 3, 2, 1 };
cout << countSwaps(A, 6);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int countSwaps( int arr[], int n)
{
HashMap<Integer,
Integer> mp = new HashMap<Integer,
Integer>();
int max_frequency = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (mp.containsKey(arr[i]))
{
mp.put(arr[i], mp.get(arr[i]) + 1 );
}
else
{
mp.put(arr[i], 1 );
}
max_frequency = Math.max(max_frequency,
mp.get(arr[i]));
}
return n - max_frequency;
}
public static void main(String[] args)
{
int A[] = { 6 , 5 , 4 , 3 , 2 , 1 };
System.out.print(countSwaps(A, 6 ));
}
}
|
Python3
def countSwaps(A, n):
mp = {}
max_frequency = 0
for i in range (n):
if A[i] in mp:
mp[A[i]] + = 1
else :
mp[A[i]] = 1
max_frequency = max (max_frequency,
mp[A[i]])
return n - max_frequency
if __name__ = = "__main__" :
A = [ 6 , 5 , 4 , 3 , 2 , 1 ]
print (countSwaps(A, 6 ))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int countSwaps( int []arr, int n)
{
Dictionary< int ,
int > mp = new Dictionary< int ,
int >();
int max_frequency = 0;
for ( int i = 0; i < n; i++)
{
if (mp.ContainsKey(arr[i]))
{
mp[arr[i]] = mp[arr[i]] + 1;
}
else
{
mp.Add(arr[i], 1);
}
max_frequency = Math.Max(max_frequency,
mp[arr[i]]);
}
return n - max_frequency;
}
public static void Main(String[] args)
{
int []A = { 6, 5, 4, 3, 2, 1 };
Console.Write(countSwaps(A, 6));
}
}
|
Javascript
<script>
function countSwaps(A, n)
{
var mp = new Map();
var max_frequency = 0;
for ( var i = 0; i < n; i++) {
if (mp.has(A[i]))
mp.set(A[i], mp.get(A[i])+1)
else
mp.set(A[i], 1);
max_frequency
= Math.max(max_frequency, mp.get(A[i]));
}
return n - max_frequency;
}
var A = [6, 5, 4, 3, 2, 1 ];
document.write( countSwaps(A, 6));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Using Using Hash Map in python:
Approach:
In this approach, a hash map can be used to store the original position of each element. The array can be sorted and the number of swaps required can be counted. While swapping, the original position of the swapped elements can be updated in the hash map. Finally, the number of elements that occupy the original position of a higher element after swapping can be counted using the hash map.
Create a dictionary with the value as the key and index as the value.
Sort the array.
Loop through the array, and for each element that is not in the correct position, swap it with the element that should be in its place, and update the dictionary accordingly. Keep track of the number of swaps performed.
Count the number of elements that replace a greater element after sorting the array.
Python3
def count_swaps(arr):
n = len (arr)
position = {arr[i]: i for i in range (n)}
arr.sort()
swaps = 0
for i in range (n):
if position[arr[i]] ! = i:
position[arr[i]], position[arr[position[arr[i]]]] = position[arr[position[arr[i]]]], position[arr[i]]
swaps + = 1
count = 0
for i in range (n - 1 ):
if arr[i] < arr[i + 1 ]:
count + = 1
return count, swaps
arr1 = [ 4 , 3 , 3 , 2 , 5 ]
arr2 = [ 6 , 5 , 4 , 3 , 2 , 1 ]
count1, swaps1 = count_swaps(arr1)
count2, swaps2 = count_swaps(arr2)
print ( "Input: A[] = {}" . format (arr1))
print ( "Output: {}" . format (count1))
print ( "Number of swaps required: {}" . format (swaps1))
print ( "Input: A[] = {}" . format (arr2))
print ( "Output: {}" . format (count2))
print ( "Number of swaps required: {}" . format (swaps2))
|
Output
Input: A[] = [2, 3, 3, 4, 5]
Output: 3
Number of swaps required: 3
Input: A[] = [1, 2, 3, 4, 5, 6]
Output: 5
Number of swaps required: 6
This approach has a time complexity of O(nlogn)
And an auxiliary space of O(n).
Similar Reads
Minimize cost of insertions and deletions required to make all array elements equal
Given a sorted array arr[] of size N (1 ? N ? 105) and two integers A and B, the task is to calculate the minimum cost required to make all array elements equal by increments or decrements. The cost of each increment and decrement are A and B respectively. Examples: Input: arr[] = { 2, 5, 6, 9, 10,
11 min read
Minimize replacements of leftmost largest array element required to make all array elements equal
Given an array arr[] consisting of N integers, the task is to make all array elements equal by replacing the leftmost largest element of the array with the largest element strictly smaller than the current maximum minimum number of times. Examples: Input: arr[] = { 1, 1, 2, 2, 3<}Output: 4Explana
6 min read
Minimize the maximum of Array by replacing any element with other element at most K times
Given an array arr[] of size N and an integer K, the task is to minimize the value of the maximum element of the array arr[] after replacing any element of the array with any other element of that array at most K times. Examples: Input: arr[] = {5, 3, 3, 2, 1}, K = 3Output: 2Explanation: Replace the
8 min read
Minimize Array sum by replacing elements such that Relation among adjacent elements in maintained
Given an array arr[] of size N, the task is to minimize the array sum after replacing array elements with positive integers in a way such the relation among the adjacent elements (pattern of the array)is maintained. Note: If arr[i] = arr[i+1] then in the new array they both can be the same or one ca
7 min read
Minimize moves required to make array elements equal by incrementing and decrementing pairs | Set 2
Given an array arr[] of size N, the task is to print the minimum number of moves required to make all array elements equal by selecting any pair of distinct indices and then increment the element at the first index and decrement the element at the other index by 1 each time. If it is impossible to m
7 min read
Minimum swaps of same indexed elements required to obtain a Majority Element in one of the arrays
Given two arrays arr[] and brr[] of length N, the task is to find the minimum number of swaps of the same indexed elements required such an element occurs at least half of the indices in the array arr[], i.e. Majority element. If it is not possible to obtain such an arrangement, then print "-1". Exa
10 min read
Make all array elements equal to 0 by replacing minimum subsequences consisting of equal elements
Given an array arr[] of size N, the task is to make all array elements equal to 0 by replacing all elements of a subsequences of equal elements by any integer, minimum number of times. Examples: Input: arr[] = {3, 7, 3}, N = 3Output: 2Explanation:Selecting a subsequence { 7 } and replacing all its e
5 min read
Minimize subarray increments/decrements required to reduce all array elements to 0
Given an array arr[], select any subarray and apply any one of the below operations on each element of the subarray: Increment by oneDecrement by one The task is to print the minimum number of above-mentioned increment/decrement operations required to reduce all array elements to 0. Examples: Input:
5 min read
Minimum swaps of similar indexed elements required to make all elements of one of the two given arrays equal
Given two arrays A[] and B[] of size N, the task is to count the minimum number of swaps of similar indexed elements required to make one of the two given arrays equal. If it is not possible to make all elements of an array equal, then print -1. Examples: Input: A[] = {3, 4, 1, 3, 1, 3, 4}, B[] = {1
12 min read
Minimize increment or increment and decrement of Pair to make all Array elements equal
Given an array arr[] of size N, the task is to minimize the number of steps to make all the array elements equal by performing the following operations: Choose an element of the array and increase it by 1.Select two elements simultaneously (arr[i], arr[j]) increase arr[i] by 1 and decrease arr[j] by
8 min read