Skip to content
Related Articles

Related Articles

Convert given Array to 0 by reducing elements pairwise with any positive value

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Hard
  • Last Updated : 02 Mar, 2022

Given an array arr[] of size N, the task is to find the number of operations to convert array elements to zero by decrementing the value of array elements in pairs by any positive value. If the array elements can’t be converted to 0, return -1.

Input: arr[] = {3, 2}
Output: -1
Explanation: All the array elements can’t be converted to 0
Input: arr[] = {5, 4, 3}
Output: 12
Explanation: Subtract 1 from pair (4, 3) we get {5, 3, 2}, subtract 3 from (5, 3) we get {2, 0, 2}, Subtract 2 from pair (2, 2) we get {0, 0, 0}

 

Approach: The task can be solved by storing all elements of an array in a priority queue, Then we need to choose pair of the two greatest elements from the queue and subtract 1 from them until only one or no positive element is left.
Follow the below steps to solve the problem:

  • Store elements in the priority queue
  • Take a while loop until the size of the priority queue is greater than or equal to 2, and in each iteration:-
    1. Pop the first two elements and store them in variables ele1 and ele2 
    2. Decrement ele1 and ele2 with 1, If any of them are still greater than zero push them again in the queue.
  • If the queue is empty print the number of operations needed, else -1

Below is the implementation of the above algorithm:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check whether
// all element of vector can
// become zero after the operations
void gfg(vector<int>& v)
{
 
    // Priroty queue to store
    // elements of vector v
    priority_queue<int> q;
 
    // Loop to store elements
    // in priroty queue
    for (auto x : v) {
        q.push(x);
    }
 
    // Stores the number
    // of operations needed
    int cnt = 0;
    while (q.size() >= 2) {
 
        // Variable to store greatest
        // element of priority queue
        int ele1 = q.top();
        q.pop();
 
        // Variable to store second greatest
        // element of priority queue
        int ele2 = q.top();
        q.pop();
 
        // Decrementing both by 1
        ele1--;
        ele2--;
        cnt += 2;
 
        // If elements are greater
        // then zero it is again
        // stored in the priority queue
        if (ele1) {
            q.push(ele1);
        }
        if (ele2) {
            q.push(ele2);
        }
    }
 
    if (q.size() == 0)
        cout << cnt << endl;
    else
        cout << -1;
}
 
// Driver code
int main()
{
 
    vector<int> v = { 5, 3, 4 };
    gfg(v);
}


Java




// Java program for the above approach
import java.util.*;
class GFG{
 
  // Function to check whether
  // all element of vector can
  // become zero after the operations
  static void gfg(int[] v)
  {
 
    // Priroty queue to store
    // elements of vector v
    PriorityQueue<Integer> q = new PriorityQueue<>(Collections.reverseOrder());
 
    // Loop to store elements
    // in priroty queue
    for (int x : v) {
      q.add(x);
    }
 
    // Stores the number
    // of operations needed
    int cnt = 0;
    while (q.size() >= 2) {
 
      // Variable to store greatest
      // element of priority queue
      int ele1 = q.peek();
      q.remove();
 
      // Variable to store second greatest
      // element of priority queue
      int ele2 = q.peek();
      q.remove();
 
      // Decrementing both by 1
      ele1--;
      ele2--;
      cnt += 2;
 
      // If elements are greater
      // then zero it is again
      // stored in the priority queue
      if (ele1>0) {
        q.add(ele1);
      }
      if (ele2>0) {
        q.add(ele2);
      }
    }
 
    if (q.size() == 0)
      System.out.print(cnt +"\n");
    else
      System.out.print(-1);
  }
 
  // Driver code
  public static void main(String[] args)
  {
 
    int[] v = { 5, 3, 4 };
    gfg(v);
  }
}
 
// This code is contributed by shikhasingrajput


Python3




# Python code for the above approach
from queue import PriorityQueue
 
# Function to check whether
# all element of vector can
# become zero after the operations
def gfg(v):
 
    # Priroty queue to store
    # elements of vector v
    q = PriorityQueue()
 
    # Loop to store elements
    # in priroty queue
    for i in range(len(v)):
        q.put(-1 * v[i])
 
    # Stores the number
    # of operations needed
    cnt = 0
    while (q.qsize() >= 2):
 
        # Variable to store greatest
        # element of priority queue
        ele1 = -1 * q.get()
 
        # Variable to store second greatest
        # element of priority queue
        ele2 = -1 * q.get()
        # Decrementing both by 1
        ele1 = ele1-1
        ele2 = ele2-1
        cnt = cnt + 2
 
        # If elements are greater
        # then zero it is again
        # stored in the priority queue
        if ele1 > 0:
            q.put(-1 * ele1)
        if ele2 > 0:
            q.put(-1 * ele2)
 
    if q.qsize() == 0:
        print(cnt)
    else:
        print(-1)
 
# Driver code
v = [5, 3, 4]
gfg(v)
 
# This code is contributed by Potta Lokesh


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG{
 
  // Function to check whether
  // all element of vector can
  // become zero after the operations
  static void gfg(int[] v)
  {
 
    // Priroty queue to store
    // elements of vector v
    List<int> q = new List<int>();
 
    // Loop to store elements
    // in priroty queue
    foreach(int x in v) {
      q.Add(x);
    }
 
    // Stores the number
    // of operations needed
    int cnt = 0;
    while (q.Count >= 2) {
 
      // Variable to store greatest
      // element of priority queue
      int ele1 = q[0];
      q.RemoveAt(0);
 
      // Variable to store second greatest
      // element of priority queue
      int ele2 = q[0];
      q.RemoveAt(0);
 
      // Decrementing both by 1
      ele1--;
      ele2--;
      cnt += 2;
 
      // If elements are greater
      // then zero it is again
      // stored in the priority queue
      if (ele1 > 0) {
        q.Add(ele1);
      }
      if (ele2 > 0) {
        q.Add(ele2);
      }
    }
 
    if (q.Count == 0)
      Console.Write(cnt +"\n");
    else
      Console.Write(-1);
  }
 
  // Driver code
  public static void Main(String[] args)
  {
 
    int[] v = { 5, 3, 4 };
    gfg(v);
  }
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
// javascript program for the above approach
 
    // Function to check whether
    // all element of vector can
    // become zero after the operations
    function gfg(v) {
 
        // Priroty queue to store
        // elements of vector v
         q = [];
 
        // Loop to store elements
        // in priroty queue
        for (x of v) {
            q.push(x);
                 
        }
q.sort((a, b)=>b - a);
 
        // Stores the number
        // of operations needed
        var cnt = 0;
        while (q.length >= 2) {
 
            // Variable to store greatest
            // element of priority queue
            var ele1 = q[0];
            q.splice(0, 1);
 
            // Variable to store second greatest
            // element of priority queue
            var ele2 = q[0];
        q.splice(0, 1);
 
            // Decrementing both by 1
            ele1 -= 1;
            ele2 -=1;
            cnt += 2;
 
            // If elements are greater
            // then zero it is again
            // stored in the priority queue
            if (ele1 > 0) {
                q.push(ele1);
            }
            if (ele2 > 0) {
                q.push(ele2);
            }
        }
 
        if (q.length == 0)
            document.write(cnt + "\n");
        else
            document.write(-1);
    }
 
    // Driver code
        var v = [ 5, 3, 4 ];
        gfg(v);
 
// This code is contributed by umadevi9616
</script>


Output

12

Time Complexity: O(N)
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!