Minimize operations to reduce Array sum by half by reducing any elements by half
Given an array Arr, the task is to find out the minimum number of operations to make the sum of array elements lesser or equal to half of its initial value. In one such operation, it is allowed to half the value of any array element.
Input: Arr = [4, 6, 3, 9, 10, 2]
Explanation: The initial sum = (4+6+3+9+10+2) = 34
1st step: choose 10 and make it 5, sum = 29
2nd step: choose 9 and make it 4, sum = 24
3rd step: choose 6 and make it 3, sum = 21
4th step: choose 5 and make it 2, sum =18
5th step: choose 4 and make it 2, sum =16
Input: Arr = [1, 5, 8, 19]
Approach: The idea to solve the problem is by using heap data structure.
The target is to reduce the number of operations to make the sum of the array half, thus,
- At every operation the amount of reduction of the sum value should be as high as possible.
- To achieve that, try to choose the maximum value available on the array and reducing it to its half value.
- The best way to find the maximum value at every iteration is to use a priority_queue as a max-heap as max-heap will store the maximum value of the array at the top of the max-heap.
To implement this approach follow these steps shown below:
- Calculate the sum of elements of the array by iterating over the array.
- Initialize a max-heap using priority_queue to store all elements of the array.
- Initialize a counter variable to 0, this variable will store the minimum number of operations.
- As the top of the max-heap will always hold the maximum element present in the array, remove the top-element, make it half (integer division) and enter the new value into the max-heap.
- Continue this previous step, until the sum of the elements become lesser than or equal to its initial value.
Below is the implementation of the above approach:
Time complexity: O(N*logN)
Auxiliary Space: O(N)