Reduce the array to atmost one element by the given operations

• Difficulty Level : Easy
• Last Updated : 13 May, 2022

Given an array of integers arr[], the task is to find the remaining element in the array after performing the following operations:

• In each turn, choose the two maximum integers X and Y from the array.
• If X == Y, remove both elements from the array.
• If X != Y, insert an element into the array equal to abs(X – Y).

Note: If no element remains, print 0.
Examples:

Input: arr[] = [3, 4, 6, 2, 7, 1]
Output:
Explanation:
Elements 7 and 6 are reduced to 1 so the array converts to [3, 4, 2, 1, 1]
Elements 3 and 4 are reduced to 2 so the array converts to [2, 1, 1, 1]
Elements 2 and 1 are reduced to 1 so the array converts to [1, 1, 1]
Element 1 is completely destroyed by another 1 so array is [1] at the end.
Input: arr[] = [1, 2, 3, 4, 5]
Output:
Explanation:
Elements 4 and 5 are reduced to 1 so the array converts to [1, 2, 3, 1]
Elements 2 and 3 are reduced to 1 so the array converts to [1, 1, 1]
Element 1 is completely destroyed by another 1 so array is [1] at the end.

Approach:
To solve the problem mentioned above, we need to use Heap Data Structure. Heaps are used because we only require the current maximum element for every instant and are not concerned about the rest of the elements.

• Create a Max Heap from the elements of the given array.
• Keep extracting the top element twice for every iteration. If their absolute difference is non-zero, push their difference back to the queue.
• Continue until only one or no elements are remaining.
• If no elements remain, print 0. Otherwise, print the remaining element.

Below is the implementation of above approach:

C++

 // C++ Program to reduce the// array to almost one element// by the given operations #include using namespace std; // Function to find the remaining// element of arrayint reduceArray(vector& arr){    priority_queue p;     // Build a priority queue    // using the array    for (int i = 0; i < arr.size(); ++i)        p.push(arr[i]);     // Continue until the priority    // queue has one or no elements    // remaining    while (p.size() > 1) {         // Top-most integer from heap        int y = p.top();        p.pop();         // Second integer from heap        int x = p.top();        p.pop();         // Resultant value        int val = y - x;        if (val != 0)            p.push(val);    }     // Return 0 if no elements are left    if (p.size() == 0)        return 0;     // Return top value of the heap    return p.top();} // Driver codeint main(){     vector arr        = { 3, 4, 6, 2, 7, 1 };    cout << reduceArray(arr)         << "\n";    return 0;}

Java

 // Java program to reduce the// array to almost one element// by the given operationsimport java.util.*; class GFG{ // Function to find the remaining// element of arraystatic int reduceArray(int[] arr){    PriorityQueue p = new PriorityQueue<>(        11, Collections.reverseOrder());     // Build a priority queue    // using the array    for(int i = 0; i < arr.length; ++i)        p.add(arr[i]);             // Continue until the priority    // queue has one or no elements    // remaining    while (p.size() > 1)    {         // Top-most integer from heap        int y = p.poll();         // Second integer from heap        int x = p.poll();                 // Resultant value        int val = y - x;        if (val != 0)            p.add(val);    }         // Return 0 if no elements are left    if (p.size() == 0)        return 0;     // Return top value of the heap    return p.poll();} // Driver codepublic static void main(String[] args){    int arr[] = { 3, 4, 6, 2, 7, 1 };         System.out.println(reduceArray(arr));}} // This code is contributed by jrishabh99

Python3

 # Python3 program to reduce the# array to almost one element# by the given operations # Function to find the remaining# element of array import heapq  def reduceArray(arr):    # Build a max heap by heapq module    # using the array    heapq._heapify_max(arr)    # Continue until the priority    # queue has one or no elements    # remaining    while len(arr) > 1:        # extracting maximum element of the max        # heap into x        x = arr[0]        # assigning last element of the heap to        # root element of the heap        arr[0] = arr[-1]        # reducing max heap size by 1        arr = arr[:-1]        # again calling heapify to maintain        # max heap property        heapq._heapify_max(arr)        # now extracting maximum element of the max        # heap into y        y = arr[0]        # assigning last element of the heap to        # root element of the heap        arr[0] = arr[-1]        # reducing max heap size by 1        arr = arr[:-1]         # finding absolute difference of x and y        val = abs(x-y)        # if both x and y are not equal, then        # inserting their absolute difference        # back into the heap        if val != 0:            arr.append(val)        # agian maintaining the max heap        # with the help of heapify()        heapq._heapify_max(arr)    if len(arr) == 0:        return 0    return arr[0]  # Driver Codearr = [3, 4, 6, 2, 7, 1]print(reduceArray(arr))'''Code is contributed by Rajat Kumar (GLAU)

Javascript



Output:

1

Time Complexity: O(NlogN)

My Personal Notes arrow_drop_up