# Minimum operations to make Array elements 0 by decrementing pair or single element

• Difficulty Level : Medium
• Last Updated : 05 Aug, 2022

Given an array arr[] of size N, the task is to find the minimum number of operations required to reduce all three elements of the array to zero. Following operations are allowed:

• Reduce 2 different array elements by one.
• Reduce a single array element by one.

#### Example:

Input: arr[] = {1, 2, 3}, N = 3
Output: 3
Explanation : Operation 1: reduce 3 and 2 to get {1, 1, 2}
Operation 2: reduuce 1 and 2 to get {1, 0, 1}
Operation 3: reduce both 1s to get {0, 0, 0}

Input: arr[] = {5, 1, 2, 9, 8}, N = 5
Output: 13

#### Approach:

This problem can be solved using greedy approach. The idea is to reduce the 2 largest elements at a time or (if not possible) 1 at a time.  As we need the largest elements in each step, we can use a max heap.

The following steps can be taken to solve this approach:

• Initiate a count variable as 0.
• Insert all the elements in a max heap.
• Reduce the two largest elements.
• Insert the reduced values again into the heap.
• Repeat above mentioned steps until all array elements become zero and increase the count at each iteration.
• Stop when all array elements are zero.

Below is the implementation of the above approach:

## Java

 `// Java program to reduce array to zero in minimum steps``import` `java.util.*;`` ` `class` `GFG {`` ` `    ``public` `static` `int` `reduceArray(``int` `arr[], ``int` `N)``    ``{`` ` `        ``int` `count = ``0``;``        ``PriorityQueue pq = ``new` `PriorityQueue<>();`` ` `        ``for` `(``int` `i = ``0``; i < N; i++) {``            ``pq.add(arr[i] * -``1``);``        ``}``        ``while` `(pq.size() > ``1``) {``            ``int` `temp1 = pq.poll();``            ``int` `temp2 = pq.poll();``            ``count++;``            ``temp1++;``            ``temp2++;``            ``if` `(temp1 != ``0``)``                ``pq.add(temp1);``            ``if` `(temp2 != ``0``)``                ``pq.add(temp2);``        ``}``        ``if` `(pq.size() > ``0``)``            ``count -= pq.poll();``        ``return` `count;``    ``}`` ` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `arr[] = { ``1``, ``2``, ``3` `};``        ``int` `N = ``3``;``        ``int` `count = reduceArray(arr, N);``        ``System.out.println(count);``    ``}``}`

Output

`3`

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

My Personal Notes arrow_drop_up