Array value by repeatedly replacing max 2 elements with their absolute difference | Java 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
import java . util . * ; class GFG { static int lastElement ( int [ ] arr ) { PriorityQueue < Integer > pq = new PriorityQueue < > ( ( a , b ) -> b - a ) ; for ( int i = 0 ; i < arr . length ; i ++ ) pq . add ( arr [ i ] ) ; int m1 , m2 ; while ( ! pq . isEmpty ( ) ) { if ( pq . size ( ) == 1 ) { return pq . poll ( ) ; } m1 = pq . poll ( ) ; m2 = pq . poll ( ) ; if ( m1 != m2 ) pq . add ( m1 - m2 ) ; } return 0 ; } public static void main ( String [ ] args ) { int [ ] arr = new int [ ] { 2 , 7 , 4 , 1 , 8 , 1 , 1 } ; System . out . println ( lastElement ( arr ) ) ; } }