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
using System ; using System . Collections . Generic ; class GFG { static void final_element ( int [ ] arr , int n ) { List < int > heap = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) heap . Add ( arr [ i ] ) ; while ( heap . Count > 1 ) { heap . Sort ( ) ; heap . Reverse ( ) ; int X = heap [ 0 ] ; heap . RemoveAt ( 0 ) ; int Y = heap [ 0 ] ; heap . RemoveAt ( 0 ) ; if ( X != Y ) { int diff = Math . Abs ( X - Y ) ; heap . Add ( diff ) ; } } if ( heap . Count == 1 ) { heap . Sort ( ) ; heap . Reverse ( ) ; Console . Write ( heap [ 0 ] ) ; } else { Console . Write ( - 1 ) ; } } static void Main ( ) { int [ ] arr = { 3 , 5 , 2 , 7 } ; int n = arr . Length ; final_element ( arr , n ) ; } }