给定一个由N 个正整数和一个整数K组成的数组arr[] ,任务是通过将数组元素拆分为最多K次的2 的幂来最小化数组的最大值。
例子:
Input: arr[] = {2, 4, 11, 2}, K = 2
Output: 2
Explanation:
Below are the operations performed on array elements at most K(= 2) times:
Operation 1: Remove the element at index 2, i.e., arr[2] = 11 and replace it with 11 numbers of 1s in it. Now the array arr[] modifies to {2, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2}.
Operation 2: Remove the element at index 1, i.e., arr[1] = 4 and replace it with 4 numbers of 1s in it. Now the array arr[] modifies to {2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2}.
After performing the above operations, the maximum value of the array is 2, which is minimum possible value.
Input: arr[]= {9}, K = 2
Output: 1
方法:给定的问题可以通过使用这样一个事实来解决,即每个数字都可以表示为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