Minimize count of given operations required to be performed to make all array elements equal to 1 | Python 3 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 math NEW_LINE def CheckAllEqual ( arr , N ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ 0 ] != arr [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def minCntOperations ( arr , N ) : NEW_LINE INDENT Max = max ( arr ) NEW_LINE isPower2 = not ( Max and ( Max & ( Max - 1 ) ) ) NEW_LINE if ( isPower2 and CheckAllEqual ( arr , N ) ) : NEW_LINE INDENT return log2 ( Max ) NEW_LINE DEDENT else : NEW_LINE INDENT return math . ceil ( math . log2 ( Max ) ) + 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minCntOperations ( arr , N ) ) NEW_LINE DEDENT