Monday, 29 Nov 2021

# Minimum operations for reducing Array to 0 by subtracting smaller element from a pair repeatedly

Given an array arr[] of size N, the task is to find the minimum number of operations required to make all array elements zero. In one operation, select a pair of elements and subtract the smaller element from both elements in the array.Example:Input: arr[] = {1, 2, 3, 4}Output: 3Explanation: Pick the elements in the following sequence:Operation 1: Pick elements at indices {3, 2}: arr[]={1, 2, 0, 1}Operation 2: Pick elements at indices {1, 3}: arr[]={1, 1, 0, 0}Operation 3: Pick elements at indices {2, 1}: arr[]={0, 0, 0, 0}Input: arr[] = {2, 2, 2, 2}Output: 2Approach:  This problem can be solved using a priority queue. To solve the below problem, follow the below steps:Traverse the array and push all the elements which are greater than 0, in the priority queue.Create a variable op, to store the number of operations, and initialise it with 0.Now, iterate over the priority queue pq till its size is greater than one in each iteration:Increment the value of variable op.Then select the top two elements, let’s say p and q to apply the given operation.After applying the operation, one element will definitely become 0. Push the other one back into the priority queue if it is greater than zero.Repeat the above operation until the priority queue becomes empty.Print op, as the answer to this question.Below is the implementation of the above approach:C++  #include using namespace std;  int setElementstoZero(int arr[], int N){          priority_queue pq;              int op = 0;      for (int i = 0; i < N; i++) {        if (arr[i] > 0) {            pq.push(arr[i]);        }    }              while (pq.size() > 1) {                op += 1;          auto p = pq.top();        pq.pop();        auto q = pq.top();        pq.pop();                          if (p – q > 0) {            pq.push(p);        }    }          return op;}  int main(){    int arr[] = { 1, 2, 3, 4 };    int N = sizeof(arr) / sizeof(arr);      cout