📌  相关文章
📜  通过将任何元素替换为其他元素最多 K 次来最小化 Array 的最大值

📅  最后修改于: 2022-05-13 01:56:05.689000             🧑  作者: Mango

通过将任何元素替换为其他元素最多 K 次来最小化 Array 的最大值

给定一个大小为N的数组arr[]和一个整数K ,任务是在将数组的任何元素替换为该数组的任何其他元素最多K次后,最小化数组arr[]的最大元素的值。

例子

解决方法:这个问题可以使用Hash map的概念来解决,思路如下:

请按照下图进行更好的理解。

插图:

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

  • 如果K = 0 ,则无法替换任何元素,则数组的最大元素保持不变。
  • 如果K ≥ N – 1 ,则将所有元素替换为最小元素,因此可以使最大值与数组的最小值相同。
  • 否则,使用映射来存储数组元素的出现次数。
  • 从数组的最大值开始遍历:
    • 如果元素的计数小于K ,则将K递减计数。
    • 否则,该元素是最小可能的最大值。
  • 返回最小可能最大值的值。

下面是上述方法的实现。

C++
// C++ code to implement the above approach
 
#include 
using namespace std;
 
// Function to minimize the maximum
// element of the array
int minimizeMax(int* arr, int N, int K)
{
    int Ans;
 
    // If K >= (N - 1), then maximum
    // element changes to minimum
    // element of array
    if (K >= (N - 1)) {
        Ans = INT_MAX;
        for (int i = 0; i < N; i++)
            Ans = min(Ans, arr[i]);
    }
 
    // If K==0, then maximum element
    // remains same
    else if (K == 0) {
        Ans = INT_MIN;
        for (int i = 0; i < N; i++)
            Ans = max(Ans, arr[i]);
    }
 
    else {
        map mp;
 
        for (int i = 0; i < N; i++) {
            mp[arr[i]]++;
        }
 
        // Create a map reverse iterator
        map::reverse_iterator it;
 
        // Traverse map from reverse and
        // if K >= Count of current
        // element then substract it from
        // k and move to next element
        // else return the element
        for (it = mp.rbegin();
             it != mp.rend(); it++) {
            if (K >= it->second)
                K -= it->second;
            else
                return it->first;
        }
    }
 
    // If any of first two conditions
    // satisfied then return Ans
    return Ans;
}
 
// Driver Code
int main()
{
    int arr[] = { 5, 3, 3, 2, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 3;
 
    // Function call
    cout << minimizeMax(arr, N, K) << endl;
    return 0;
}


Java
// Java code to implement the above approach
import java.io.*;
import java.util.*;
 
class GFG
{
 
  // Function to minimize the maximum
  // element of the array
  public static int minimizeMax(int arr[], int N, int K)
  {
    int ans = 0;
 
    // If K >= (N - 1), then maximum
    // element changes to minimum
    // element of array
    if (K >= (N - 1)) {
      ans = Integer.MAX_VALUE;
      for (int i = 0; i < N; i++)
        ans = Math.min(ans, arr[i]);
    }
 
    // If K==0, then maximum element
    // remains same
    else if (K == 0) {
      ans = Integer.MIN_VALUE;
      for (int i = 0; i < N; i++)
        ans = Math.max(ans, arr[i]);
    }
 
    else
    {
 
      // Creating a map in descending order of keys
      TreeMap mp
        = new TreeMap<>(Collections.reverseOrder());
 
      for (int i = 0; i < N; i++) {
        if (mp.get(arr[i]) != null)
          mp.put(arr[i], mp.get(arr[i]) + 1);
        else
          mp.put(arr[i], 1);
      }
 
      // Traverse map and
      // if K >= Count of current
      // element then substract it from
      // k and move to next element
      // else return the element
      for (Map.Entry ele :
           mp.entrySet()) {
        if (K >= ele.getValue())
          K -= ele.getValue();
        else
          return ele.getKey();
      }
    }
 
    // If any of first two conditions
    // satisfied then return Ans
    return ans;
  }
  public static void main(String[] args)
  {
    int arr[] = { 5, 3, 3, 2, 1 };
    int N = 5;
    int K = 3;
 
    // Function call
    System.out.println(minimizeMax(arr, N, K));
  }
}
 
// This code is contributed by Rohit Pradhan.


Python3
# Python code to implement the above approach
 
# Function to minimize the maximum
# element of the array
def minimizeMax(arr, N, K):
    Ans = 0
 
    # If K >= (N - 1), then maximum
    # element changes to minimum
    # element of array
    if (K >= (N - 1)):
        Ans = sys.maxsize
        for i in range(0, N):
            Ans = min(Ans, arr[i])
 
    # If K==0, then maximum element
    # remains same
    elif (K == 0):
        Ans = -1*sys.maxsize
        for i in range(0, N):
            Ans = max(Ans, arr[i])
 
    else:
        mp = dict()
 
        for i in range(N):
            if arr[i] in mp.keys():
                mp[arr[i]] += 1
            else:
                mp[arr[i]] = 1
 
        # Traverse map from reverse and
        # if K >= Count of current
        # element then substract it from
        # k and move to next element
        # else return the element
        for x in mp:
            if (K >= mp[x]):
                K -= mp[x]
            else:
                return x
 
    # If any of first two conditions
    # satisfied then return Ans
    return Ans
 
# Driver Code
arr = [5, 3, 3, 2, 1]
N = len(arr)
K = 3
 
# Function call
print(minimizeMax(arr, N, K))
 
# This code is contributed by Taranpreet


输出
2

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