text: Array value by repeatedly replacing max 2 elements with their absolute difference | C ++ 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 . ; 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 ; finally return 0 ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int lastElement ( vector < int > & arr ) { priority_queue < int > pq ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { pq . push ( arr [ i ] ) ; } int m1 , m2 ; while ( ! pq . empty ( ) ) { if ( pq . size ( ) == 1 ) return pq . top ( ) ; m1 = pq . top ( ) ; pq . pop ( ) ; m2 = pq . top ( ) ; pq . pop ( ) ; if ( m1 != m2 ) pq . push ( m1 - m2 ) ; } return 0 ; } int main ( ) { vector < int > arr = { 2 , 7 , 4 , 1 , 8 , 1 , 1 } ; cout << lastElement ( arr ) << endl ; return 0 ; }