Wednesday, November 27, 2024
Google search engine
HomeData Modelling & AIArray value by repeatedly replacing max 2 elements with their absolute difference

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:
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 = 1-1 = 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++




// 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;
}
 
// This code is contributed by shinjanpatra


C




// 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;
}


Java




// Java program to find the array value
// by repeatedly replacing max 2 elements
// with their absolute difference
import java.util.*;
 
class GFG{
     
// Function that return last
// value of array
static int lastElement(int[] arr)
{
     
    // Build a binary max_heap
    PriorityQueue<Integer> pq = new PriorityQueue<>(
                                (a, b) -> b - a);
     
    for(int i = 0; i < arr.length; i++)
        pq.add(arr[i]);
     
    // For max 2 elements
    int m1, m2;
     
    // Iterate until queue is not empty
    while(!pq.isEmpty())
    {
         
        // If only 1 element is left
        if (pq.size() == 1)
        {
             
            // Return the last
            // remaining value
            return pq.poll();
        }
         
        m1 = pq.poll();
        m2 = pq.poll();
         
        // Check that difference
        // is non zero
        if (m1 != m2)
            pq.add(m1 - m2);
    }
     
    // Finally return 0
    return 0;
}
 
// Driver code
public static void main(String[] args)
{
    int[] arr = new int[]{2, 7, 4, 1, 8, 1, 1 };
     
    System.out.println(lastElement(arr));
}
}
 
// This code is contributed by dadi madhav


Python3




# 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)):
         
        # Multiplying 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


C#




// C# program to find the array value
// by repeatedly replacing max 2 elements
// with their absolute difference
using System;
using System.Collections.Generic;
  
class GFG{
  
// Function that return last
// value of array
static int lastElement(int[] arr)
{
     
    // Build a binary max_heap
    Queue<int> pq = new Queue<int>();
      
    for(int i = 0; i < arr.Length; i++)
        pq.Enqueue(arr[i]);
      
    // For max 2 elements
    int m1, m2;
      
    // Iterate until queue is not empty
    while (pq.Contains(0))
    {
         
        // If only 1 element is left
        if (pq.Count == 1)
        {
             
            // Return the last
            // remaining value
            return pq.Peek();
        }
          
        m1 = pq.Dequeue();
        m2 = pq.Peek();
          
        // Check that difference
        // is non zero
        if (m1 != m2)
            pq.Enqueue(m1 - m2);
    }
     
    // Finally return 0
    return 0;
}
  
// Driver Code
public static void Main(String[] args)
{
    int[] arr = { 2, 7, 4, 1, 8, 1, 1 };
      
    Console.WriteLine(lastElement(arr));
}
}
 
// This code is contributed by sanjoy_62


Javascript




<script>
 
// JavaScript program to find the array value
// by repeatedly replacing max 2 elements
// with their absolute difference
 
// function that return last
// value of array
function lastElement(arr) {
    // Build a binary max_heap.
    let pq = [];
    for (let i = 0; i < arr.length; i++) {
        pq.push(arr[i]);
    }
 
    // For max 2 elements
    let m1, m2;
 
    // Iterate until queue is not empty
    while (pq.length) {
 
        // if only 1 element is left
        if (pq.length == 1)
 
            // return the last
            // remaining value
            return pq[pq.length - 1];
 
        pq.sort((a, b) => a - b)
        m1 = pq[pq.length - 1];
        pq.pop();
        m2 = pq[pq.length - 1];
        pq.pop();
 
        // check that difference
        // is non zero
        if (m1 != m2)
            pq.push(m1 - m2);
    }
 
    // finally return 0
    return 0;
}
 
// Driver Code
 
let arr = [2, 7, 4, 1, 8, 1, 1];
 
document.write(lastElement(arr) + "<br>");
 
</script>


Output: 

0

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

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments