Last element remaining by deleting two largest elements and replacing by their absolute difference if they are unequal | Java 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
import java . io . * ; import java . util . Collections ; import java . util . * ; class GFG { static public int final_element ( Integer [ ] arr , int n ) { if ( arr == null ) { return 0 ; } PriorityQueue < Integer > heap = new PriorityQueue < Integer > ( Collections . reverseOrder ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { heap . offer ( arr [ i ] ) ; } while ( heap . size ( ) > 1 ) { int X = heap . poll ( ) ; int Y = heap . poll ( ) ; if ( X != Y ) { int diff = Math . abs ( X - Y ) ; heap . offer ( diff ) ; } } return heap . size ( ) == 1 ? heap . poll ( ) : - 1 ; } public static void main ( String [ ] args ) { Integer arr [ ] = new Integer [ ] { 3 , 5 , 2 , 7 } ; int n = arr . length ; System . out . println ( final_element ( arr , n ) ) ; } }