Minimum operations required to make every element greater than or equal to K | Java implementation of above approach ; Function to calculate gcd of two numbers ; Java function to get minimum operation needed ; The priority queue holds a minimum element in the top position ; push value one by one from the given array ; store count of minimum operation needed ; All elements are now >= k ; It is impossible to make as there are no sufficient elements available ; Take two smallest elements and replace them by their LCM first smallest element ; Second smallest element ; Increment the count ; Driver code
import java . util . PriorityQueue ; class GFG { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static int FindMinOperation ( int [ ] a , int n , int k ) { PriorityQueue < Integer > Q = new PriorityQueue < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) Q . add ( a [ i ] ) ; int ans = 0 ; while ( true ) { if ( Q . peek ( ) >= k ) break ; if ( Q . size ( ) < 2 ) return - 1 ; int x = Q . peek ( ) ; Q . poll ( ) ; int y = Q . peek ( ) ; Q . poll ( ) ; int z = ( x * y ) / gcd ( x , y ) ; Q . add ( z ) ; ans ++ ; } return ans ; } public static void main ( String [ ] args ) { int [ ] a = { 3 , 5 , 7 , 6 , 8 } ; int k = 8 ; int n = a . length ; System . out . println ( FindMinOperation ( a , n , k ) ) ; } }