Minimize count of given operations required to be performed to make all array elements equal to 1 | Java program to implement the above approach ; Function to check if all array elements are equal or not ; Traverse the array ; If all array elements are not equal ; Function to find minimum count of operation to make all the array elements equal to 1 ; Stores largest element of the array ; Check if a number is a power of 2 or not ; If Max is a power of 2 and all array elements are equal ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static boolean CheckAllEqual ( int arr [ ] , int N ) { for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ 0 ] != arr [ i ] ) { return false ; } } return true ; } static int minCntOperations ( int arr [ ] , int N ) { int Max = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; boolean isPower2 ; if ( ( int ) ( Math . ceil ( ( Math . log ( N ) / Math . log ( N ) ) ) ) == ( int ) ( Math . floor ( ( ( Math . log ( N ) / Math . log ( 2 ) ) ) ) ) ) { isPower2 = true ; } else { isPower2 = false ; } if ( isPower2 && CheckAllEqual ( arr , N ) ) { return ( int ) ( Math . log ( Max ) / Math . log ( 2 ) ) ; } else { return ( int ) Math . ceil ( Math . log ( Max ) / Math . log ( 2 ) ) + 1 ; } } public static void main ( String [ ] args ) { int [ ] arr = new int [ ] { 2 , 4 } ; int N = arr . length ; System . out . println ( minCntOperations ( arr , N ) ) ; } }