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
using System ; using System . Collections . Generic ; class GFG { static int lastElement ( int [ ] arr ) { Queue < int > pq = new Queue < int > ( ) ; for ( int i = 0 ; i < arr . Length ; i ++ ) pq . Enqueue ( arr [ i ] ) ; int m1 , m2 ; while ( pq . Contains ( 0 ) ) { if ( pq . Count == 1 ) { return pq . Peek ( ) ; } m1 = pq . Dequeue ( ) ; m2 = pq . Peek ( ) ; if ( m1 != m2 ) pq . Enqueue ( m1 - m2 ) ; } return 0 ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 7 , 4 , 1 , 8 , 1 , 1 } ; Console . WriteLine ( lastElement ( arr ) ) ; } }