Minimum operations required to make every element greater than or equal to K | C ++ implementation of above approach ; C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int FindMinOperation ( int a [ ] , int n , int k ) { priority_queue < int , vector < int > , greater < int > > Q ; for ( int i = 0 ; i < n ; i ++ ) Q . push ( a [ i ] ) ; int ans = 0 ; while ( 1 ) { if ( Q . top ( ) >= k ) break ; if ( Q . size ( ) < 2 ) return -1 ; int x = Q . top ( ) ; Q . pop ( ) ; int y = Q . top ( ) ; Q . pop ( ) ; int z = ( x * y ) / __gcd ( x , y ) ; Q . push ( z ) ; ans ++ ; } return ans ; } int main ( ) { int a [ ] = { 3 , 5 , 7 , 6 , 8 } ; int k = 8 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << FindMinOperation ( a , n , k ) ; }