Last element remaining by deleting two largest elements and replacing by their absolute difference if they are unequal | Python3 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 . Default priority queue in Python is min - heap so use - 1 * arr [ i ] ; Perform operation until heap size becomes 0 or 1 ; Remove largest element ; Remove 2 nd largest element ; If extracted elements 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
from queue import PriorityQueue NEW_LINE def final_element ( arr , n ) : NEW_LINE INDENT heap = PriorityQueue ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT heap . put ( - 1 * arr [ i ] ) NEW_LINE DEDENT while ( heap . qsize ( ) > 1 ) : NEW_LINE INDENT X = - 1 * heap . get ( ) NEW_LINE Y = - 1 * heap . get ( ) NEW_LINE if ( X != Y ) : NEW_LINE INDENT diff = abs ( X - Y ) NEW_LINE heap . put ( - 1 * diff ) NEW_LINE DEDENT DEDENT if ( heap . qsize ( ) == 1 ) : NEW_LINE INDENT print ( - 1 * heap . get ( ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 5 , 2 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE final_element ( arr , n ) NEW_LINE DEDENT