in ,

Sum of Array maximums after K operations by reducing max element to its half

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.


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:



using namespace std;


int maxValue(vector<int> arr, int K)



    int val = 0;




    priority_queue<int> pq(arr.begin(),





    while (K--) {



        int max =;




        val += max;



        pq.push(max / 2);




    return val;



int main()


    vector<int> arr = { 2, 4, 6, 8, 10 };

    int K = 5;

    cout << maxValue(arr, K);


Time Complexity: O(K*log N)
Auxiliary Space: O(N)

What do you think?

Silver 1

Written by yulica

Leave a Reply

Your email address will not be published.

      Minimize operations to convert (0, 0) to (N, M) by incrementing either or both by K

      SCAND Is Celebrating Its 20th Anniversary_61d8c28bb0417.jpeg

      SCAND Is Celebrating Its 20th Anniversary