Skip to content
Related Articles

Related Articles

Minimize operations to reduce Array sum by half by reducing any elements by half

View Discussion
Improve Article
Save Article
  • Last Updated : 05 Jul, 2022

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.

Examples:

Input: Arr[] = [4, 6, 3, 9, 10, 2]
Output: 5
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]
Output: 3

 

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:

C++




// C++ code for the above approach:
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find minimum operations
int minops(vector<int>& nums)
{
    int sum = 0;
    for (auto x : nums)
        sum += x;
 
    // Initializing max heap
    priority_queue<int> pq;
    for (auto x : nums) {
        pq.push(x);
    }
    double temp = sum;
    int cnt = 0;
    while (temp > sum / 2) {
        int x = pq.top();
        pq.pop();
        temp -= ceil(x * 1.0 / 2);
        pq.push(x / 2);
        cnt++;
    }
 
    // Return count
    return cnt;
}
 
// Driver code
int main()
{
 
    vector<int> nums = { 4, 6, 3, 9, 10, 2 };
    int count = minops(nums);
    cout << count << endl;
}


Java




import java.util.*;
import java.io.*;
 
// Java program for the above approach
class GFG{
 
  // Function to find minimum operations
  static int minops(ArrayList<Integer> nums)
  {
    int sum = 0;
    for(int i = 0 ; i < nums.size() ; i++){
      sum += nums.get(i);
    }
 
    // Initializing max heap
    PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
    for(int i = 0 ; i < nums.size() ; i++){
      pq.add(-nums.get(i));
    }
 
    double temp = sum;
    int cnt = 0;
    while (temp > sum / 2) {
      int x = -pq.peek();
      pq.remove();
      temp -= Math.ceil(x * 1.0 / 2);
      pq.add(x / 2);
      cnt++;
    }
 
    // Return count
    return cnt;
  }
 
  // Driver code
  public static void main(String args[])
  {
    ArrayList<Integer> nums = new ArrayList<Integer>(
      List.of(
        4, 6, 3, 9, 10, 2
      )
    );
    int count = minops(nums);
    System.out.println(count);
  }
}
 
// This code is contributed by entertain2022.


Python3




# python code for the above approach:
# importing the required moduls
import math
import heapq as hq
 
# Function to find minimum operations
def minops(nums):
    summ = 0
    for i in nums:
        summ += i
         
    # assigning nums list to pq for making it max heap
    pq = nums
     
    # initializing max heap
    hq._heapify_max(pq)
    temp = summ
    cnt = 0
 
    while (temp > summ/2):
        x = pq[0]
        pq[0] = pq[-1]
        pq.pop()
        hq._heapify_max(pq)
        temp -= math.ceil(x*1.0/2)
        pq.append(x/2)
        cnt += 1
         
    # Return count
    return cnt
 
# Driver code
if __name__ == "__main__":
    nums = [4, 6, 3, 9, 10, 2]
    count = minops(nums)
    print(count)
     
 # This code is written by Rajat Kumar.......


Javascript




// JavaScript code for the above approach:
 
// Function to find minimum operations
function minops(nums)
{
    let sum = 0;
    for (let a of nums)
        sum += a;
 
    // Initializing max heap
    let pq = [];
    for (let a of nums) {
        pq.push(a);
    }
    pq.sort();
    pq.reverse();
    let temp = sum;
    let cnt = 0;
    while (temp > (sum / 2)) {
        let x = pq[0];
        pq[0] = pq[pq.length - 1];
        pq.splice(pq.length - 1, 1);
        temp -= (Math.floor(x * 1.0 / 2)  + 1);
        pq.push(x / 2);
        pq.sort();
        pq.reverse();
        cnt++;
    }
 
    // Return count
    return cnt;
}
 
// Driver code
let  nums = [ 4, 6, 3, 9, 10, 2 ];
let count = minops(nums);
console.log(count);
 
// This code is contributed by phasing17.


Output

5

Time complexity: O(N*logN)
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!