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.
Input: arr = [2, 7, 4, 1, 8, 1]
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 = .
Input: arr = [7, 10, 5, 4, 11, 25]
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:
Time Complexity: O(N)
Auxiliary Complexity: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer DSA Live Classes