📌  相关文章
📜  通过替换K最小化最大和最小数组元素之间的差异

📅  最后修改于: 2021-04-22 07:23:00             🧑  作者: Mango

给定一个由N个整数组成的数组A [] ,任务是在替换K个元素之后找到给定数组中最大和最小元素之间的最小差。

例子:

排序方法:想法是对给定的数组进行排序。检查从数组的开头删除X ( 0≤X≤K )个元素并从数组的结尾删除K – X个元素的所有K + 1种可能性,并计算出最小差值。最后,打印获得的最小差异。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find minimum difference
// between largest and smallest element
// after K replacements
int minDiff(int A[], int K, int n)
{
     
    // Sort array in ascending order
    sort(A, A + n);
     
    if (n <= K)
        return 0;
 
    // Minimum difference
    int mindiff = A[n - 1] - A[0];
     
    if (K == 0)
        return mindiff;
 
    // Check for all K + 1 possibilities
    for(int i = 0, j = n - 1 - K; j < n;)
    {
        mindiff = min(
            mindiff, A[j] - A[i]);
 
        i++;
        j++;
    }
 
    // Return answer
    return mindiff;
}
 
// Driver Code
int main()
{
     
    // Given array
    int A[] = { -1, 3, -1, 8, 5, 4 };
    int K = 3;
     
    // Length of array
    int n = sizeof(A) / sizeof(A[0]);
     
    // Prints the minimum possible difference
    cout << minDiff(A, K, n);
     
    return 0;
}
 
// This code is contributed by 29AjayKumar


Java
// Java program for the above approach
 
import java.util.*;
 
class GFG {
 
    // Function to find minimum difference
    // between largest and smallest element
    // after K replacements
    static int minDiff(int[] A, int K)
    {
        // Sort array in ascending order
        Arrays.sort(A);
 
        // Length of array
        int n = A.length;
 
        if (n <= K)
            return 0;
 
        // Minimum difference
        int mindiff = A[n - 1] - A[0];
        if (K == 0)
            return mindiff;
 
        // Check for all K + 1 possibilities
        for (int i = 0, j = n - 1 - K; j < n;) {
            mindiff = Math.min(
                mindiff, A[j] - A[i]);
 
            i++;
            j++;
        }
 
        // Return answer
        return mindiff;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array
        int A[] = { -1, 3, -1, 8, 5, 4 };
        int K = 3;
 
        // Prints the minimum possible difference
        System.out.println(minDiff(A, K));
    }
}


Python3
# Python3 program for the above approach
 
# Function to find minimum difference
# between largest and smallest element
# after K replacements
def minDiff(A, K):
   
    # Sort array in ascending order
    A.sort();
 
    # Length of array
    n = len(A);
    if (n <= K):
        return 0;
 
    # Minimum difference
    mindiff = A[n - 1] - A[0];
    if (K == 0):
        return mindiff;
 
    # Check for all K + 1 possibilities
    i = 0;
    for j in range(n - 1 - K, n):
        mindiff = min(mindiff, A[j] - A[i]);
 
        i += 1;
        j += 1;
 
    # Return answer
    return mindiff;
 
# Driver Code
if __name__ == '__main__':
     
    # Given array
    A = [-1, 3, -1, 8, 5, 4];
    K = 3;
 
    # Prints the minimum possible difference
    print(minDiff(A, K));
 
    # This code is contributed by 29AjayKumar


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to find minimum difference
// between largest and smallest element
// after K replacements
static int minDiff(int[] A, int K)
{
     
    // Sort array in ascending order
    Array.Sort(A);
 
    // Length of array
    int n = A.Length;
 
    if (n <= K)
        return 0;
 
    // Minimum difference
    int mindiff = A[n - 1] - A[0];
     
    if (K == 0)
        return mindiff;
 
    // Check for all K + 1 possibilities
    for(int i = 0, j = n - 1 - K; j < n;)
    {
        mindiff = Math.Min(
            mindiff, A[j] - A[i]);
 
        i++;
        j++;
    }
 
    // Return answer
    return mindiff;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array
    int []A = { -1, 3, -1, 8, 5, 4 };
    int K = 3;
 
    // Prints the minimum possible difference
    Console.WriteLine(minDiff(A, K));
}
}
 
// This code is contributed by shikhasingrajput


C++
// C++ program for above approach
#include 
using namespace std;
 
// Function to find minimum difference
// between the largest and smallest
// element after K replacements
int minDiff(int A[], int K, int N)
{
    if (N <= K + 1)
        return 0;
 
    // Create a MaxHeap
    priority_queue, greater>
        maxHeap;
 
    // Create a MinHeap
    priority_queue minHeap;
 
    // Update maxHeap and MinHeap with highest
    // and smallest K elements respectively
    for (int i = 0; i < N; i++)
    {
 
        // Insert current element
        // into the MaxHeap
        maxHeap.push(A[i]);
 
        // If maxHeap size exceeds K + 1
        if (maxHeap.size() > K + 1)
 
            // Remove top element
            maxHeap.pop();
 
        // Insert current element
        // into the MaxHeap
        minHeap.push(A[i]);
 
        // If maxHeap size exceeds K + 1
        if (minHeap.size() > K + 1)
 
            // Remove top element
            minHeap.pop();
    }
 
    // Store all max element from maxHeap
    vector maxList;
    while (maxHeap.size() > 0)
    {
        maxList.push_back(maxHeap.top());
        maxHeap.pop();
    }
 
    // Store all min element from minHeap
    vector minList;
    while (minHeap.size() > 0)
    {
        minList.push_back(minHeap.top());
        minHeap.pop();
    }
 
    int mindiff = INT_MAX;
 
    // Generating all K + 1 possibilities
    for (int i = 0; i <= K; i++)
    {
        mindiff = min(mindiff, maxList[i] - minList[K - i]);
    }
   
    // Return answer
    return mindiff;
}
 
// Driver Code
int main()
{
 
    // Given array
    int A[] = { -1, 3, -1, 8, 5, 4 };
    int N = sizeof(A) / sizeof(A[0]);
    int K = 3;
 
    // Function call
    cout << minDiff(A, K, N);
    return 0;
}
 
// This code is contributed by Dharanendra L V


Java
// Java program for above approach
 
import java.util.*;
import java.lang.*;
 
class GFG {
 
    // Function to find minimum difference
    // between the largest and smallest
    // element after K replacements
    static int minDiff(int[] A, int K)
    {
        if (A.length <= K + 1)
            return 0;
 
        // Create a MaxHeap
        PriorityQueue maxHeap
            = new PriorityQueue<>();
 
        // Create a MinHeap
        PriorityQueue minHeap
            = new PriorityQueue<>(
                Collections.reverseOrder());
 
        // Update maxHeap and MinHeap with highest
        // and smallest K elements respectively
        for (int n : A) {
 
            // Insert current element
            // into the MaxHeap
            maxHeap.add(n);
 
            // If maxHeap size exceeds K + 1
            if (maxHeap.size() > K + 1)
 
                // Remove top element
                maxHeap.poll();
 
            // Insert current element
            // into the MaxHeap
            minHeap.add(n);
 
            // If maxHeap size exceeds K + 1
            if (minHeap.size() > K + 1)
 
                // Remove top element
                minHeap.poll();
        }
 
        // Store all max element from maxHeap
        List maxList = new ArrayList<>();
        while (maxHeap.size() > 0)
            maxList.add(maxHeap.poll());
 
        // Store all min element from minHeap
        List minList = new ArrayList<>();
        while (minHeap.size() > 0)
            minList.add(minHeap.poll());
 
        int mindiff = Integer.MAX_VALUE;
 
        // Generating all K + 1 possibilities
        for (int i = 0; i <= K; i++) {
            mindiff = Math.min(mindiff,
                               maxList.get(i)
                                   - minList.get(K - i));
        }
        // Return answer
        return mindiff;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Given array
        int A[] = { -1, 3, -1, 8, 5, 4 };
        int K = 3;
 
        // Function call
        System.out.println(minDiff(A, K));
    }
}


Python3
# Python3 program for above approach
import sys
 
# Function to find minimum difference
# between the largest and smallest
# element after K replacements
def minDiff(A, K) :
    if (len(A) <= K + 1) :
        return 0
          
    # Create a MaxHeap
    maxHeap = []
  
    # Create a MinHeap
    minHeap = []
  
    # Update maxHeap and MinHeap with highest
    # and smallest K elements respectively
    for n in A :
          
        # Insert current element
        # into the MaxHeap
        maxHeap.append(n)
        maxHeap.sort()
          
        # If maxHeap size exceeds K + 1
        if (len(maxHeap) > K + 1) :
  
            # Remove top element
            del maxHeap[0]
  
        # Insert current element
        # into the MaxHeap
        minHeap.append(n)
        minHeap.sort()
        minHeap.reverse()
          
        # If maxHeap size exceeds K + 1
        if (len(minHeap) > K + 1) :
  
            # Remove top element
            del minHeap[0]
      
    # Store all max element from maxHeap
    maxList = []
      
    while (len(maxHeap) > 0) :
     
        maxList.append(maxHeap[0])
        del maxHeap[0]
      
    # Store all min element from minHeap
    minList = []
      
    while (len(minHeap) > 0) : 
        minList.append(minHeap[0])
        del minHeap[0]
    mindiff = sys.maxsize
  
    # Generating all K + 1 possibilities
    for i in range(K) :
     
        mindiff = min(mindiff, maxList[i] - minList[K - i])
      
    # Return answer
    return mindiff
     
# Given array
A = [ -1, 3, -1, 8, 5, 4 ]
K = 3
  
# Function call
print(minDiff(A, K))
 
# This code is contributed by divyesh072019.


C#
// C# program for above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to find minimum difference
// between the largest and smallest
// element after K replacements
static int minDiff(int[] A, int K)
{
    if (A.Length <= K + 1)
        return 0;
         
    // Create a MaxHeap
    List maxHeap = new List();
 
    // Create a MinHeap
    List minHeap = new List();
 
    // Update maxHeap and MinHeap with highest
    // and smallest K elements respectively
    foreach(int n in A)
    {
         
        // Insert current element
        // into the MaxHeap
        maxHeap.Add(n);
        maxHeap.Sort();
         
        // If maxHeap size exceeds K + 1
        if (maxHeap.Count > K + 1)
 
            // Remove top element
            maxHeap.RemoveAt(0);
 
        // Insert current element
        // into the MaxHeap
        minHeap.Add(n);
        minHeap.Sort();
        minHeap.Reverse();
         
        // If maxHeap size exceeds K + 1
        if (minHeap.Count > K + 1)
 
            // Remove top element
            minHeap.RemoveAt(0);
    }
     
    // Store all max element from maxHeap
    List maxList = new List();
     
    while (maxHeap.Count > 0)
    {
        maxList.Add(maxHeap[0]);
        maxHeap.RemoveAt(0);
    }
     
    // Store all min element from minHeap
    List minList = new List();
     
    while (minHeap.Count > 0)
    {
        minList.Add(minHeap[0]);
        minHeap.RemoveAt(0);
    }
     
    int mindiff = Int32.MaxValue;
 
    // Generating all K + 1 possibilities
    for(int i = 0; i < K; i++)
    {
        mindiff = Math.Min(mindiff,
                           maxList[i] -
                           minList[K - i]);
    }
     
    // Return answer
    return mindiff;
}
 
// Driver code
static void Main()
{
     
    // Given array
    int[] A = { -1, 3, -1, 8, 5, 4 };
    int K = 3;
     
    // Function call
    Console.WriteLine(minDiff(A, K));
}
}
 
// This code is contributed by divyeshrabadiya07


输出:
2

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

基于的方法:此方法与上述方法相似。分别使用Min Heap和Max Heap查找K个最小和K个最大数组元素。

请按照以下步骤解决问题:

  1. 初始化两个PriorityQueues, min-heapmax-heap
  2. 遍历给定的数组,并将所有元素一一添加到堆中。如果堆的大小超过K ,则在任何堆中,删除该队列顶部存在的元素。
  3. K个最大值和最小值元素存储在两个单独的数组maxListminList中,并初始化变量minDiff来存储最小差异。
  4. 遍历阵列和对于每个指数,说,更新MINDIFFMINDIFF =分钟(MINDIFF,maxList [I] -minList [K – 1])和打印MINDIFF的最终值作为所需答案。

下面是上述方法的实现:

C++

// C++ program for above approach
#include 
using namespace std;
 
// Function to find minimum difference
// between the largest and smallest
// element after K replacements
int minDiff(int A[], int K, int N)
{
    if (N <= K + 1)
        return 0;
 
    // Create a MaxHeap
    priority_queue, greater>
        maxHeap;
 
    // Create a MinHeap
    priority_queue minHeap;
 
    // Update maxHeap and MinHeap with highest
    // and smallest K elements respectively
    for (int i = 0; i < N; i++)
    {
 
        // Insert current element
        // into the MaxHeap
        maxHeap.push(A[i]);
 
        // If maxHeap size exceeds K + 1
        if (maxHeap.size() > K + 1)
 
            // Remove top element
            maxHeap.pop();
 
        // Insert current element
        // into the MaxHeap
        minHeap.push(A[i]);
 
        // If maxHeap size exceeds K + 1
        if (minHeap.size() > K + 1)
 
            // Remove top element
            minHeap.pop();
    }
 
    // Store all max element from maxHeap
    vector maxList;
    while (maxHeap.size() > 0)
    {
        maxList.push_back(maxHeap.top());
        maxHeap.pop();
    }
 
    // Store all min element from minHeap
    vector minList;
    while (minHeap.size() > 0)
    {
        minList.push_back(minHeap.top());
        minHeap.pop();
    }
 
    int mindiff = INT_MAX;
 
    // Generating all K + 1 possibilities
    for (int i = 0; i <= K; i++)
    {
        mindiff = min(mindiff, maxList[i] - minList[K - i]);
    }
   
    // Return answer
    return mindiff;
}
 
// Driver Code
int main()
{
 
    // Given array
    int A[] = { -1, 3, -1, 8, 5, 4 };
    int N = sizeof(A) / sizeof(A[0]);
    int K = 3;
 
    // Function call
    cout << minDiff(A, K, N);
    return 0;
}
 
// This code is contributed by Dharanendra L V

Java

// Java program for above approach
 
import java.util.*;
import java.lang.*;
 
class GFG {
 
    // Function to find minimum difference
    // between the largest and smallest
    // element after K replacements
    static int minDiff(int[] A, int K)
    {
        if (A.length <= K + 1)
            return 0;
 
        // Create a MaxHeap
        PriorityQueue maxHeap
            = new PriorityQueue<>();
 
        // Create a MinHeap
        PriorityQueue minHeap
            = new PriorityQueue<>(
                Collections.reverseOrder());
 
        // Update maxHeap and MinHeap with highest
        // and smallest K elements respectively
        for (int n : A) {
 
            // Insert current element
            // into the MaxHeap
            maxHeap.add(n);
 
            // If maxHeap size exceeds K + 1
            if (maxHeap.size() > K + 1)
 
                // Remove top element
                maxHeap.poll();
 
            // Insert current element
            // into the MaxHeap
            minHeap.add(n);
 
            // If maxHeap size exceeds K + 1
            if (minHeap.size() > K + 1)
 
                // Remove top element
                minHeap.poll();
        }
 
        // Store all max element from maxHeap
        List maxList = new ArrayList<>();
        while (maxHeap.size() > 0)
            maxList.add(maxHeap.poll());
 
        // Store all min element from minHeap
        List minList = new ArrayList<>();
        while (minHeap.size() > 0)
            minList.add(minHeap.poll());
 
        int mindiff = Integer.MAX_VALUE;
 
        // Generating all K + 1 possibilities
        for (int i = 0; i <= K; i++) {
            mindiff = Math.min(mindiff,
                               maxList.get(i)
                                   - minList.get(K - i));
        }
        // Return answer
        return mindiff;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Given array
        int A[] = { -1, 3, -1, 8, 5, 4 };
        int K = 3;
 
        // Function call
        System.out.println(minDiff(A, K));
    }
}

Python3

# Python3 program for above approach
import sys
 
# Function to find minimum difference
# between the largest and smallest
# element after K replacements
def minDiff(A, K) :
    if (len(A) <= K + 1) :
        return 0
          
    # Create a MaxHeap
    maxHeap = []
  
    # Create a MinHeap
    minHeap = []
  
    # Update maxHeap and MinHeap with highest
    # and smallest K elements respectively
    for n in A :
          
        # Insert current element
        # into the MaxHeap
        maxHeap.append(n)
        maxHeap.sort()
          
        # If maxHeap size exceeds K + 1
        if (len(maxHeap) > K + 1) :
  
            # Remove top element
            del maxHeap[0]
  
        # Insert current element
        # into the MaxHeap
        minHeap.append(n)
        minHeap.sort()
        minHeap.reverse()
          
        # If maxHeap size exceeds K + 1
        if (len(minHeap) > K + 1) :
  
            # Remove top element
            del minHeap[0]
      
    # Store all max element from maxHeap
    maxList = []
      
    while (len(maxHeap) > 0) :
     
        maxList.append(maxHeap[0])
        del maxHeap[0]
      
    # Store all min element from minHeap
    minList = []
      
    while (len(minHeap) > 0) : 
        minList.append(minHeap[0])
        del minHeap[0]
    mindiff = sys.maxsize
  
    # Generating all K + 1 possibilities
    for i in range(K) :
     
        mindiff = min(mindiff, maxList[i] - minList[K - i])
      
    # Return answer
    return mindiff
     
# Given array
A = [ -1, 3, -1, 8, 5, 4 ]
K = 3
  
# Function call
print(minDiff(A, K))
 
# This code is contributed by divyesh072019.

C#

// C# program for above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to find minimum difference
// between the largest and smallest
// element after K replacements
static int minDiff(int[] A, int K)
{
    if (A.Length <= K + 1)
        return 0;
         
    // Create a MaxHeap
    List maxHeap = new List();
 
    // Create a MinHeap
    List minHeap = new List();
 
    // Update maxHeap and MinHeap with highest
    // and smallest K elements respectively
    foreach(int n in A)
    {
         
        // Insert current element
        // into the MaxHeap
        maxHeap.Add(n);
        maxHeap.Sort();
         
        // If maxHeap size exceeds K + 1
        if (maxHeap.Count > K + 1)
 
            // Remove top element
            maxHeap.RemoveAt(0);
 
        // Insert current element
        // into the MaxHeap
        minHeap.Add(n);
        minHeap.Sort();
        minHeap.Reverse();
         
        // If maxHeap size exceeds K + 1
        if (minHeap.Count > K + 1)
 
            // Remove top element
            minHeap.RemoveAt(0);
    }
     
    // Store all max element from maxHeap
    List maxList = new List();
     
    while (maxHeap.Count > 0)
    {
        maxList.Add(maxHeap[0]);
        maxHeap.RemoveAt(0);
    }
     
    // Store all min element from minHeap
    List minList = new List();
     
    while (minHeap.Count > 0)
    {
        minList.Add(minHeap[0]);
        minHeap.RemoveAt(0);
    }
     
    int mindiff = Int32.MaxValue;
 
    // Generating all K + 1 possibilities
    for(int i = 0; i < K; i++)
    {
        mindiff = Math.Min(mindiff,
                           maxList[i] -
                           minList[K - i]);
    }
     
    // Return answer
    return mindiff;
}
 
// Driver code
static void Main()
{
     
    // Given array
    int[] A = { -1, 3, -1, 8, 5, 4 };
    int K = 3;
     
    // Function call
    Console.WriteLine(minDiff(A, K));
}
}
 
// This code is contributed by divyeshrabadiya07
输出:
2

时间复杂度: O(NlogN)其中N是给定数组的大小。
辅助空间: O(N)