Last element remaining by deleting two largest elements and replacing by their absolute difference if they are unequal | C ++ program for the above approach ; Function to print the remaining element ; Priority queue can be used to construct max - heap ; Insert all element of arr [ ] into priority queue ; Perform operation until heap size becomes 0 or 1 ; Remove largest element ; Remove 2 nd largest element ; If extracted element are not equal ; Find X - Y and push it to heap ; If heap size is 1 , then print the remaining element ; Else print " - 1" ; Driver Code ; Given array arr [ ] ; Size of array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int final_element ( int arr [ ] , int n ) { priority_queue < int > heap ; for ( int i = 0 ; i < n ; i ++ ) heap . push ( arr [ i ] ) ; while ( heap . size ( ) > 1 ) { int X = heap . top ( ) ; heap . pop ( ) ; int Y = heap . top ( ) ; heap . pop ( ) ; if ( X != Y ) { int diff = abs ( X - Y ) ; heap . push ( diff ) ; } } if ( heap . size ( ) == 1 ) { cout << heap . top ( ) ; } else { cout << " - 1" ; } } int main ( ) { int arr [ ] = { 3 , 5 , 2 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; final_element ( arr , n ) ; return 0 ; }