Minimize remaining array element by removing pairs and replacing them with their average | Java program to implement the above approach ; Function to find the smallest element left in the array by removing pairs and inserting their average ; Stores array elements such that the largest element present at top of PQ ; Traverse the array ; Insert arr [ i ] into PQ ; Iterate over elements of PQ while count of elements in PQ greater than 1 ; Stores largest element of PQ ; Pop the largest element of PQ ; Stores largest element of PQ ; Pop the largest element of PQ ; Insert the ceil value of average of top1 and top2 ; Driver Code
import java . util . PriorityQueue ; class GFG { static int findSmallestNumLeft ( int arr [ ] , int N ) { PriorityQueue < Integer > PQ = new PriorityQueue < Integer > ( ( a , b ) -> b - a ) ; for ( int i = 0 ; i < N ; i ++ ) { PQ . add ( arr [ i ] ) ; } while ( PQ . size ( ) > 1 ) { int top1 = PQ . peek ( ) ; PQ . remove ( ) ; int top2 = PQ . peek ( ) ; PQ . remove ( ) ; PQ . add ( ( top1 + top2 + 1 ) / 2 ) ; } return PQ . peek ( ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 30 , 16 , 40 } ; int N = arr . length ; System . out . print ( findSmallestNumLeft ( arr , N ) ) ; } }