Last element remaining by deleting two largest elements and replacing by their absolute difference if they are unequal | 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" ; Given array arr [ ] ; Size of array arr [ ] ; Function Call
function final_element ( arr , n ) { var heap = [ ] ; for ( var i = 0 ; i < n ; i ++ ) heap . push ( arr [ i ] ) ; heap . sort ( ( a , b ) => a - b ) ; while ( heap . length > 1 ) { var X = heap [ heap . length - 1 ] ; heap . pop ( ) ; var Y = heap [ heap . length - 1 ] ; heap . pop ( ) ; if ( X != Y ) { var diff = Math . abs ( X - Y ) ; heap . push ( diff ) ; } heap . sort ( ( a , b ) => a - b ) ; } if ( heap . length == 1 ) { document . write ( heap [ heap . length - 1 ] ) ; } else { document . write ( " " ) ; } } var arr = [ 3 , 5 , 2 , 7 ] ; var n = arr . length ; final_element ( arr , n ) ;