📌  相关文章
📜  最小化交换以最大化元素数量,以替换数组中的更大元素

📅  最后修改于: 2021-05-04 18:46:34             🧑  作者: Mango

给定一个由N个元素组成的数组A [] ,任务是找到所需交换的最小数量,以使交换来替换原始数组中较高元素的数组元素最大化。

例子:

天真的方法:解决问题的最简单方法可以实现如下:

  • 以升序对数组进行排序。
  • 初始化两个变量result index ,分别存储在原始数组中已考虑的计数和索引。
  • 遍历数组元素。对于任何元素A [i] ,转到数组中大于i的值,并相应地增加index变量。
  • 找到大于A [i]的元素后,将结果递增,并将index递增。
  • 如果索引已到达数组的末尾,则没有元素可与先前检查的元素交换。
  • 因此,请打印计数

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Function to find the minimum
// number of swaps required
int countSwaps(int A[], int n)
{
    // Sort the array in ascending order
    sort(A, A + n);
 
    int ind = 1, res = 0;
 
    for (int i = 0; i < n; i++) {
 
        // Iterate until a greater element
        // is found
        while (ind < n and A[ind] == A[i])
 
            // Keep incrementing ind
            ind++;
 
        // If a greater element is found
        if (ind < n and A[ind] > A[i]) {
 
            // Increase count of swap
            res++;
 
            // Increment ind
            ind++;
        }
 
        // If end of array is reached
        if (ind >= n)
            break;
    }
 
    // Return the answer
    return res;
}
 
// Driver Code
int main()
{
 
    int A[] = { 4, 3, 3, 2, 5 };
    cout << countSwaps(A, 5);
 
    return 0;
}


Java
// Java Program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to find the minimum
// number of swaps required
static int countSwaps(int A[], int n)
{
    // Sort the array in ascending order
    Arrays.sort(A);
    int ind = 1, res = 0;
 
    for (int i = 0; i < n; i++)
    {
 
        // Iterate until a greater element
        // is found
        while (ind < n && A[ind] == A[i])
 
            // Keep incrementing ind
            ind++;
 
        // If a greater element is found
        if (ind < n && A[ind] > A[i])
        {
 
            // Increase count of swap
            res++;
 
            // Increment ind
            ind++;
        }
 
        // If end of array is reached
        if (ind >= n)
            break;
    }
 
    // Return the answer
    return res;
}
 
// Driver Code
public static void main(String[] args)
{
    int A[] = { 4, 3, 3, 2, 5 };
    System.out.print(countSwaps(A, 5));
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 program to implement
# the above approach
 
# Function to find the minimum
# number of swaps required
def countSwaps(A, n):
 
    # Sort the array in ascending order
    A.sort()
 
    ind, res = 1, 0
 
    for i in range(n):
 
        # Iterate until a greater element
        # is found
        while (ind < n and A[ind] == A[i]):
 
            # Keep incrementing ind
            ind += 1
 
        # If a greater element is found
        if (ind < n and A[ind] > A[i]):
 
            # Increase count of swap
            res += 1
 
            # Increment ind
            ind += 1
 
        # If end of array is reached
        if (ind >= n):
            break
 
    # Return the answer
    return res
 
# Driver Code
A = [ 4, 3, 3, 2, 5 ]
 
print (countSwaps(A, 5))
 
# This code is contributed by chitranayal


C#
// C# Program to implement
// the above approach
using System;
class GFG{
 
// Function to find the minimum
// number of swaps required
static int countSwaps(int []A, int n)
{
    // Sort the array in ascending order
    Array.Sort(A);
    int ind = 1, res = 0;
 
    for (int i = 0; i < n; i++)
    {
 
        // Iterate until a greater element
        // is found
        while (ind < n && A[ind] == A[i])
 
            // Keep incrementing ind
            ind++;
 
        // If a greater element is found
        if (ind < n && A[ind] > A[i])
        {
 
            // Increase count of swap
            res++;
 
            // Increment ind
            ind++;
        }
 
        // If end of array is reached
        if (ind >= n)
            break;
    }
 
    // Return the answer
    return res;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []A = { 4, 3, 3, 2, 5 };
    Console.Write(countSwaps(A, 5));
}
}
 
// This code is contributed by Amit Katiyar


C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Function to find the minimum
// number of swaps required
int countSwaps(int A[], int n)
{
    // Stores the frequency of the
    // array elements
    map mp;
 
    // Stores maximum frequency
    int max_frequency = 0;
 
    // Find the max frequency
    for (int i = 0; i < n; i++) {
 
        // Update frequency
        mp[A[i]]++;
 
        // Update maximum frequency
        max_frequency
            = max(max_frequency, mp[A[i]]);
    }
 
    return n - max_frequency;
}
 
// Driver Code
int main()
{
 
    int A[] = { 6, 5, 4, 3, 2, 1 };
 
    // function call
    cout << countSwaps(A, 6);
 
    return 0;
}


Java
// Java Program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to find the minimum
// number of swaps required
static int countSwaps(int arr[], int n)
{
    // Stores the frequency of the
    // array elements
    HashMap mp = new HashMap();
 
    // Stores maximum frequency
    int max_frequency = 0;
 
    // Find the max frequency
    for (int i = 0; i < n; i++)
    {
 
        // Update frequency
        if(mp.containsKey(arr[i]))
        {
            mp.put(arr[i], mp.get(arr[i]) + 1);
        }
        else
        {
            mp.put(arr[i], 1);
        }
 
        // Update maximum frequency
        max_frequency = Math.max(max_frequency,
                                 mp.get(arr[i]));
    }
    return n - max_frequency;
}
 
// Driver Code
public static void main(String[] args)
{
    int A[] = { 6, 5, 4, 3, 2, 1 };
 
    // function call
    System.out.print(countSwaps(A, 6));
}
}
 
// This code is contributed by Rohit_ranjan


Python3
# Python3 Program to implement
# the above approach
 
# Function to find the minimum
# number of swaps required
def countSwaps(A, n):
     
    # Stores the frequency of the
    # array elements
    mp = {}
 
    # Stores maximum frequency
    max_frequency = 0
 
    # Find the max frequency
    for i in range(n):
 
        # Update frequency
        if A[i] in mp:
            mp[A[i]] += 1
        else:
            mp[A[i]] = 1
 
        # Update maximum frequency
        max_frequency = max(max_frequency,
                            mp[A[i]])
 
    return n - max_frequency
   
# Driver code
if __name__ == "__main__":   
 
      A = [6, 5, 4, 3, 2, 1]
     
    # function call
    print(countSwaps(A, 6))
 
# This code is contributed by divyeshrabadiya07


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the minimum
// number of swaps required
static int countSwaps(int []arr, int n)
{
     
    // Stores the frequency of the
    // array elements
    Dictionary mp = new Dictionary();
 
    // Stores maximum frequency
    int max_frequency = 0;
 
    // Find the max frequency
    for(int i = 0; i < n; i++)
    {
         
        // Update frequency
        if(mp.ContainsKey(arr[i]))
        {
            mp[arr[i]] = mp[arr[i]] + 1;
        }
        else
        {
            mp.Add(arr[i], 1);
        }
 
        // Update maximum frequency
        max_frequency = Math.Max(max_frequency,
                                 mp[arr[i]]);
    }
    return n - max_frequency;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []A = { 6, 5, 4, 3, 2, 1 };
 
    // Function call
    Console.Write(countSwaps(A, 6));
}
}
 
// This code is contributed by 29AjayKumar


输出:
3

时间复杂度: O(N * log N)
辅助空间: O(1)
高效方法:
由于两个不相等元素之间的任何交换都会导致元素替换较高的元素,因此可以观察到,所需交换的最小数量为N –(数组元素的最大频率) 。因此,使用HashMap在数组中找到最频繁的元素,然后打印结果。
下面是上述方法的实现:

C++

// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Function to find the minimum
// number of swaps required
int countSwaps(int A[], int n)
{
    // Stores the frequency of the
    // array elements
    map mp;
 
    // Stores maximum frequency
    int max_frequency = 0;
 
    // Find the max frequency
    for (int i = 0; i < n; i++) {
 
        // Update frequency
        mp[A[i]]++;
 
        // Update maximum frequency
        max_frequency
            = max(max_frequency, mp[A[i]]);
    }
 
    return n - max_frequency;
}
 
// Driver Code
int main()
{
 
    int A[] = { 6, 5, 4, 3, 2, 1 };
 
    // function call
    cout << countSwaps(A, 6);
 
    return 0;
}

Java

// Java Program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to find the minimum
// number of swaps required
static int countSwaps(int arr[], int n)
{
    // Stores the frequency of the
    // array elements
    HashMap mp = new HashMap();
 
    // Stores maximum frequency
    int max_frequency = 0;
 
    // Find the max frequency
    for (int i = 0; i < n; i++)
    {
 
        // Update frequency
        if(mp.containsKey(arr[i]))
        {
            mp.put(arr[i], mp.get(arr[i]) + 1);
        }
        else
        {
            mp.put(arr[i], 1);
        }
 
        // Update maximum frequency
        max_frequency = Math.max(max_frequency,
                                 mp.get(arr[i]));
    }
    return n - max_frequency;
}
 
// Driver Code
public static void main(String[] args)
{
    int A[] = { 6, 5, 4, 3, 2, 1 };
 
    // function call
    System.out.print(countSwaps(A, 6));
}
}
 
// This code is contributed by Rohit_ranjan

Python3

# Python3 Program to implement
# the above approach
 
# Function to find the minimum
# number of swaps required
def countSwaps(A, n):
     
    # Stores the frequency of the
    # array elements
    mp = {}
 
    # Stores maximum frequency
    max_frequency = 0
 
    # Find the max frequency
    for i in range(n):
 
        # Update frequency
        if A[i] in mp:
            mp[A[i]] += 1
        else:
            mp[A[i]] = 1
 
        # Update maximum frequency
        max_frequency = max(max_frequency,
                            mp[A[i]])
 
    return n - max_frequency
   
# Driver code
if __name__ == "__main__":   
 
      A = [6, 5, 4, 3, 2, 1]
     
    # function call
    print(countSwaps(A, 6))
 
# This code is contributed by divyeshrabadiya07

C#

// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the minimum
// number of swaps required
static int countSwaps(int []arr, int n)
{
     
    // Stores the frequency of the
    // array elements
    Dictionary mp = new Dictionary();
 
    // Stores maximum frequency
    int max_frequency = 0;
 
    // Find the max frequency
    for(int i = 0; i < n; i++)
    {
         
        // Update frequency
        if(mp.ContainsKey(arr[i]))
        {
            mp[arr[i]] = mp[arr[i]] + 1;
        }
        else
        {
            mp.Add(arr[i], 1);
        }
 
        // Update maximum frequency
        max_frequency = Math.Max(max_frequency,
                                 mp[arr[i]]);
    }
    return n - max_frequency;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []A = { 6, 5, 4, 3, 2, 1 };
 
    // Function call
    Console.Write(countSwaps(A, 6));
}
}
 
// This code is contributed by 29AjayKumar
输出:
5

时间复杂度: O(N)
辅助空间: O(N)