Given an array arr[] of N integers and an integer K, the task is to find the sum of maximum of the array possible wherein each operation the current maximum of the array is replaced with its half.
Example:
Input: arr[] = {2, 4, 6, 8, 10}, K = 5
Output: 33
Explanation: In 1st operation, the maximum of the given array is 10. Hence, the value becomes 10 and the array after 1st operation becomes arr[] = {2, 4, 6, 8, 5}.
The value after 2nd operation = 18 and arr[] = {2, 4, 6, 4, 5}.
Similarly, proceeding forward, value after 5th operation will be 33.Input: arr[] = {6, 5}, K = 3
Output: 14
Approach: The given problem can be solved with the help of a greedy approach. The idea is to use a max heap data structure. Therefore, traverse the given array and insert all the elements in the array arr[] into a max priority queue. At each operation, remove the maximum from the heap using pop operation, add it to the value and reinsert the value after dividing it by two into the heap. The value after repeating the above operation K times is the required answer.
Below is the implementation of the above approach:
C++
|
Time Complexity: O(K*log N)
Auxiliary Space: O(N)