Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Minimize cost for reducing array by replacing two elements with sum at most K times for any index
Next article icon

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

Last Updated : 16 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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. 
C#
// C# code for the above approach using System; using System.Collections.Generic;  public class GFG {     // Function to find minimum operations     static int MinOps(List<int> nums)     {         int sum = 0;         foreach (var x in nums)             sum += x;          // Initializing max heap         SortedSet<int> pq = new SortedSet<int>(nums, Comparer<int>.Create((a, b) => b.CompareTo(a)));         double temp = sum;         int cnt = 0;         while (temp > sum / 2)         {             int x = pq.Min;             pq.Remove(x);             temp -= Math.Ceiling(x * 1.0 / 2);             pq.Add(x / 2);             cnt++;         }          // Return count         return cnt;     }      static void Main(string[] args)     {         List<int> nums = new List<int> { 4, 6, 3, 9, 10, 2 };         int count = MinOps(nums);         Console.WriteLine(count);     } } 

Output
5

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


Next Article
Minimize cost for reducing array by replacing two elements with sum at most K times for any index

S

shinjanpatra
Improve
Article Tags :
  • Greedy
  • DSA
  • Arrays
Practice Tags :
  • Arrays
  • Greedy

Similar Reads

  • Minimize Cost to reduce the Array to a single element by given operations
    Given an array a[] consisting of N integers and an integer K, the task is to find the minimum cost to reduce the given array to a single element by choosing any pair of consecutive array elements and replace them by (a[i] + a[i+1]) for a cost K * (a[i] + a[i+1]). Examples: Input: a[] = {1, 2, 3}, K
    15+ min read
  • Minimize cost for reducing array by replacing two elements with sum at most K times for any index
    Given an array arr[] of size N and an integer K. The task is to find the minimum cost required to collect the sum of the array. The sum of the array is collected by picking any element and adding it to an element of any index in the array. The addition of elements at the same index is allowed for at
    11 min read
  • Minimize array length by repeatedly replacing pairs of unequal adjacent array elements by their sum
    Given an integer array arr[], the task is to minimize the length of the given array by repeatedly replacing two unequal adjacent array elements by their sum. Once the array is reduced to its minimum possible length, i.e. no adjacent unequal pairs are remaining in the array, print the count of operat
    6 min read
  • Minimum operations to make all Array elements 0 by MEX replacement
    Given an array of N integers. You can perform an operation that selects a contiguous subarray and replaces all its elements with the MEX (smallest non-negative integer that does not appear in that subarray), the task is to find the minimum number of operations required to make all the elements of th
    5 min read
  • Minimize Array sum by replacing L and R elements from both end with X and Y
    Given an array A[] of N integers and 2 integers X and Y. The task is to minimize the sum of all elements of the array by choosing L and R and replacing the initial L elements with X and the R elements from the end with Y. Examples: Input: N = 5, X = 4, Y = 3, A[] = {5, 5, 0, 6, 3}Output: 14Explanati
    8 min read
  • Minimize Array elements to be reduced to make subsequences sum 1 to Array max possible
    Given an array a[] of positive integers. Subtract any positive integer from any number of elements of the array such that there exists every possible subsequence with sum 1 to s, where s denotes the sum of all the elements of the array. Find the minimum possible number of the array element to be sub
    6 min read
  • Minimize steps to make Array elements equal by using giving operations
    Given an arr[] of length N. Then the task is to find minimum steps to make all the elements of the given array equal. Two types of operations can be performed as given below: Choose a prefix of size K, where arr[K] = max element in that chosen sub-array and convert all elements equal to max. Choose
    8 min read
  • Make all array elements equal by reducing array elements to half minimum number of times
    Given an array arr[] consisting of N integers, the task is to minimize the number of operations required to make all array elements equal by converting Ai to Ai / 2. in each operation Examples: Input: arr[] = {3, 1, 1, 3}Output: 2Explanation: Reducing A0 to A0 / 2 modifies arr[] to {1, 1, 1, 3}. Red
    6 min read
  • Minimize the sum of MEX by removing all elements of array
    Given an array of integers arr[] of size N. You can perform the following operation N times: Pick any index i, and remove arr[i] from the array and add MEX(arr[]) i.e., Minimum Excluded of the array arr[] to your total score. Your task is to minimize the total score. Examples: Input: N = 8, arr[] =
    7 min read
  • Minimize remaining array element by repeatedly replacing pairs by half of one more than their sum
    Given an array arr[] containing a permutation of first N natural numbers. In one operation, remove a pair (X, Y) from the array and insert (X + Y + 1) / 2 into the array. The task is to find the smallest array element that can be left remaining in the array by performing the given operation exactly
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences