Maximize count of distinct elements possible in an Array from the given operation | Java program to find the maximum possible distinct elements that can be obtained from the array by performing the given operations ; Function to find the gcd of two numbers ; Function to calculate and return the count of maximum possible distinct elements in the array ; Find the maximum element ; Base Case ; Finding the gcd of first two element ; Calculate Gcd of the array ; Return the total count of distinct elements ; Driver code
import java . util . * ; class GFG { static int gcd ( int x , int y ) { if ( x == 0 ) return y ; return gcd ( y % x , x ) ; } static int findDistinct ( int arr [ ] , int n ) { int maximum = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; if ( n == 1 ) return 1 ; if ( n == 2 ) { return ( maximum / gcd ( arr [ 0 ] , arr [ 1 ] ) ) ; } int k = gcd ( arr [ 0 ] , arr [ 1 ] ) ; for ( int i = 2 ; i < n ; i ++ ) { k = gcd ( k , arr [ i ] ) ; } return ( maximum / k ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 5 } ; int n = arr . length ; System . out . println ( findDistinct ( arr , n ) ) ; } }