Minimize count of given operations required to be performed to make all array elements equal to 1 | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool CheckAllEqual ( int arr [ ] , int N ) { for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ 0 ] != arr [ i ] ) { return false ; } } return true ; } int minCntOperations ( int arr [ ] , int N ) { int Max = * max_element ( arr , arr + N ) ; bool isPower2 = ! ( Max && ( Max & ( Max - 1 ) ) ) ; if ( isPower2 && CheckAllEqual ( arr , N ) ) { return log2 ( Max ) ; } else { return ceil ( log2 ( Max ) ) + 1 ; } } int main ( ) { int arr [ ] = { 2 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minCntOperations ( arr , N ) ; }