text: Minimum number of given operations required to reduce the array to 0 element | C ++ implementation of the approach ; Function to return the minimum operations required ; Count the frequency of each element ; Maximum element from the array ; Find all the multiples of i ; Delete the multiples ; Increment the operations ; Driver code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( int * arr , int n ) { int maxi , result = 0 ; vector < int > freq ( 1000001 , 0 ) ; for ( int i = 0 ; i < n ; i ++ ) { int x = arr [ i ] ; freq [ x ] ++ ; } maxi = * ( max_element ( arr , arr + n ) ) ; for ( int i = 1 ; i <= maxi ; i ++ ) { if ( freq [ i ] != 0 ) { for ( int j = i * 2 ; j <= maxi ; j = j + i ) { freq [ j ] = 0 ; } result ++ ; } } return result ; } int main ( ) { int arr [ ] = { 2 , 4 , 2 , 4 , 4 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minOperations ( arr , n ) ; return 0 ; }