Array value by repeatedly replacing max 2 elements with their absolute difference

Given an array arr size N, the task is to print the final array value remaining in the array when the maximum and second maximum element of the array is replaced by their absolute difference in the array, repeatedly.

Note: If the maximum two elements are same, then both are removed from the array, without replacing any value.

Examples:
Input: arr = [2, 7, 4, 1, 8, 1]
Output: 1
Explanations:
Merging 7 and 8: absolute difference = 7 – 8 = 1. So the array converted into [2, 4, 1, 1, 1].
Merging 2 and 4: absolute difference = 4 – 2 = 2. So the array converted into [2, 1, 1, 1].
Merging 2 and 1: absolute difference = 2 – 1 = 1. So the array converted into [1, 1, 1].
Merging 1 and 1: absolute difference = 4 – 2 = 0. So nothing will be Merged.
So final array = [1].

Input: arr = [7, 10, 5, 4, 11, 25]
Output: 2

Efficient Approach: Using Priority Queue



  • Make a priority queue(binary max heap) which automatically arrange the element in sorted order.
  • Then pick the first element (which is maximum) and 2nd element(2nd max), if both are equal then don’t push anything, if not equal push absolute difference of both in queue.
  • Do the above steps till queue size is equal to 1, then return last element. If queue becomes empty before reaching size 1, then return 0.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find the array value
// by repeatedly replacing max 2 elements
// with their absolute difference
  
#include <bits/stdc++.h>
using namespace std;
  
// function that return last
// value of array
int lastElement(vector<int>& arr)
{
    // Build a binary max_heap.
    priority_queue<int> pq;
    for (int i = 0; i < arr.size(); i++) {
        pq.push(arr[i]);
    }
  
    // For max 2 elements
    int m1, m2;
  
    // Iterate until queue is not empty
    while (!pq.empty()) {
  
        // if only 1 element is left
        if (pq.size() == 1)
  
// return the last
// remaining value
            return pq.top();
  
        m1 = pq.top();
        pq.pop();
        m2 = pq.top();
        pq.pop();
  
        // check that difference
        // is non zero
        if (m1 != m2)
            pq.push(m1 - m2);
    }
  
    // finally return 0
    return 0;
}
  
// Driver Code
int main()
{
    vector<int> arr = { 2, 7, 4, 1, 8, 1, 1 };
  
    cout << lastElement(arr) << endl;
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find the array value 
# by repeatedly replacing max 2 elements 
# with their absolute difference 
from queue import PriorityQueue
  
# Function that return last 
# value of array 
def lastElement(arr):
      
    # Build a binary max_heap.
    pq = PriorityQueue()
    for i in range(len(arr)):
          
        # Multipying by -1 for 
        # max heap
        pq.put(-1 * arr[i])
      
    # For max 2 elements 
    m1 = 0
    m2 = 0
      
    # Iterate until queue is not empty
    while not pq.empty():
      
        # If only 1 element is left 
        if pq.qsize() == 1:
              
            # Return the last 
            # remaining value 
            return -1 * pq.get()
        else:
            m1 = -1 * pq.get()
            m2 = -1 * pq.get()
              
        # Check that difference 
        # is non zero 
        if m1 != m2 :
            pq.put(-1 * abs(m1 - m2))
              
    return 0
      
# Driver Code 
arr = [ 2, 7, 4, 1, 8, 1, 1 ]
  
print(lastElement(arr))
  
# This code is contributed by ishayadav181

chevron_right


Output:

0

Time Complexity: O(N)
Auxillary Complexity: O(N)

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : ishayadav181