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

20 Jan, 2022
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 = 5Output: 33Explanation: 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 = 3Output: 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++
Java
Python3
// C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Function to find maximum possible// value after K given operationsint maxValue(vector<int> arr, int K){    // Stores required value    int val = 0;     // Initializing priority queue    // with all elements of array    priority_queue<int> pq(arr.begin(),                           arr.end());     // Loop to iterate through    // each operation    while (K--) {         // Current Maximum        int max = pq.top();        pq.pop();         // Update value        val += max;         // Reinsert maximum        pq.push(max / 2);    }     // Return Answer    return val;} // Driver Callint main(){    vector<int> arr = { 2, 4, 6, 8, 10 };    int K = 5;    cout << maxValue(arr, K);}
// Java code for the above approachimport java.util.Comparator;import java.util.PriorityQueue;class CustomComparator implements Comparator<Integer> {   @Override  public int compare(Integer number1, Integer number2)  {    int value =  number1.compareTo(number2);     // elements are sorted in reverse order    if (value > 0) {      return -1;    }    else if (value < 0) {      return 1;    }    else {      return 0;    }  }}class GFG {   // Function to find maximum possible  // value after K given operations  static int maxValue(int[] arr, int K)  {     // Stores required value    int val = 0;     // Initializing priority queue    // with all elements of array    PriorityQueue<Integer> pq      = new PriorityQueue<Integer>(new CustomComparator());     for (int i = 0; i < arr.length; i++) {      pq.add(arr[i]);    }     // Loop to iterate through    // each operation    while (K != 0) {       // Current Maximum      int max = pq.poll();       // Update value      val += max;       // Reinsert maximum      pq.add((int)Math.floor(max / 2));      K = K - 1;    }     // Return Answer    return val;  }   // Driver Call  public static void main(String[] args)  {    int[] arr = { 2, 4, 6, 8, 10 };    int K = 5;    System.out.println(maxValue(arr, K));  }} // This code is conbtributed by Potta Lokesh
# python3 program of the above approachfrom queue import PriorityQueue # Function to find maximum possible# value after K given operationsdef maxValue(arr, K):     # Stores required value    val = 0     # Initializing priority queue    # with all elements of array    pq = PriorityQueue()     for dt in arr:        pq.put(-1*dt)     # Loop to iterate through    # each operation    while (True):         # Current Maximum        max = -1 * pq.get()         # Update value        val += max         # Reinsert maximum        pq.put(-1 * (max // 2))         K -= 1         if K == 0:            break     # Return Answer    return val # Driver Callif __name__ == "__main__":     arr = [2, 4, 6, 8, 10]    K = 5    print(maxValue(arr, K))     # This code is contributed by rakeshsahni
  
33
 
Time Complexity: O(K*log N)Auxiliary Space: O(N)
 
rakeshsahni
lokeshpotta20
Algo-Geek 2021
Algo Geek
Arrays
Heap
Queue
Arrays
Queue
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check if the given string is valid English word or not
Sort strings on the basis of their numeric part
Divide given number into two even parts
Smallest set of vertices to visit all nodes of the given Graph
Count of Palindrome Strings in given Array of strings
Arrays in Java
Arrays in C/C++
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Program for array rotation