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
function lastElement ( arr ) { let pq = [ ] ; for ( let i = 0 ; i < arr . length ; i ++ ) { pq . push ( arr [ i ] ) ; } let m1 , m2 ; while ( pq . length ) { if ( pq . length == 1 ) return pq [ pq . length - 1 ] ; pq . sort ( ( a , b ) => a - b ) m1 = pq [ pq . length - 1 ] ; pq . pop ( ) ; m2 = pq [ pq . length - 1 ] ; pq . pop ( ) ; if ( m1 != m2 ) pq . push ( m1 - m2 ) ; } return 0 ; } let arr = [ 2 , 7 , 4 , 1 , 8 , 1 , 1 ] ; document . write ( lastElement ( arr ) + " " ) ;