Array value by repeatedly replacing max 2 elements with their absolute difference | Python3 program to find the array value by repeatedly replacing max 2 elements with their absolute difference ; Function that return last value of array ; Build a binary max_heap . ; Multipying by - 1 for max heap ; For max 2 elements ; Iterate until queue is not empty ; If only 1 element is left ; Return the last remaining value ; Check that difference is non zero ; Driver Code
from queue import PriorityQueue NEW_LINE def lastElement ( arr ) : NEW_LINE INDENT pq = PriorityQueue ( ) NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT pq . put ( - 1 * arr [ i ] ) NEW_LINE DEDENT m1 = 0 NEW_LINE m2 = 0 NEW_LINE while not pq . empty ( ) : NEW_LINE INDENT if pq . qsize ( ) == 1 : NEW_LINE INDENT return - 1 * pq . get ( ) NEW_LINE DEDENT else : NEW_LINE INDENT m1 = - 1 * pq . get ( ) NEW_LINE m2 = - 1 * pq . get ( ) NEW_LINE DEDENT if m1 != m2 : NEW_LINE INDENT pq . put ( - 1 * abs ( m1 - m2 ) ) NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT arr = [ 2 , 7 , 4 , 1 , 8 , 1 , 1 ] NEW_LINE print ( lastElement ( arr ) ) NEW_LINE