Minimum number of given operations required to reduce the array to 0 element | Java 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
import java . util . Arrays ; class GFG { static int minOperations ( int [ ] arr , int n ) { int maxi , result = 0 ; int [ ] freq = new int [ 1000001 ] ; for ( int i = 0 ; i < n ; i ++ ) { int x = arr [ i ] ; freq [ x ] ++ ; } maxi = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; 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 ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 2 , 4 , 4 , 4 } ; int n = arr . length ; System . out . println ( minOperations ( arr , n ) ) ; } }