📌  相关文章
📜  通过将数组元素拆分为最多 K 次的 2 次幂来最小化最大数组元素

📅  最后修改于: 2021-09-06 06:52:49             🧑  作者: Mango

给定一个由N 个正整数和一个整数K组成的数组arr[] ,任务是通过将数组元素拆分为最多K次的2 的幂来最小化数组的最大值。

例子:

方法:给定的问题可以通过使用这样一个事实来解决,即每个数字都可以表示为1的和,即2请按照以下步骤解决问题:

  • 按降序对数组 arr[] 进行排序。
  • 查找数组arr[]中 0 的计数,如果 count 的值为N ,则打印0作为结果数组的最小最大值
  • 否则,如果K的值至少为 N ,则打印1作为数组的结果最小最大值
  • 否则,将arr[K]的值打印为数组的结果最小最大值。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the minimum value
// of the maximum element of the array
// by splitting at most K array element
// into perfect powers of 2
void minimumSize(int arr[], int N, int K)
{
    // Sort the array element in
    // the ascending order
    sort(arr, arr + N);
 
    // Reverse the array
    reverse(arr, arr + N);
 
    // If count of 0 is equal to N
    if (count(arr, arr + N, 0) == N)
        cout << 0;
 
    // Otherwise, if K is greater
    // than or equal to N
    else if (K >= N)
        cout << 1 << endl;
 
    // Otherwise
    else
        cout << arr[K] << endl;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 4, 8, 2 };
    int K = 2;
    int N = sizeof(arr) / sizeof(arr[0]);
    minimumSize(arr, N, K);
 
    return 0;
}


Python
# Python program for the above approach
 
# Function to find the minimum value
# of the maximum element of the array
# by splitting at most K array element
# into perfect powers of 2
def minimumSize(arr, N, K):
   
    # Sort the array element in
    # the ascending order
    arr.sort()
     
    # Reverse the array
    arr.reverse()
     
    # If count of 0 is equal to N
    zero = arr.count(0)
    if zero == N:
        print(0)
         
    # Otherwise, if K is greater
    # than or equal to N
    elif K >= N:
        print(1)
         
    # Otherwise
    else:
        print(arr[K])
 
# Driver Code
arr = [2, 4, 8, 2]
K = 2
N = len(arr)
minimumSize(arr, N, K)
 
# This code is contributed by sudhanshugupta2019a.


输出:
2

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live