Maximize difference between odd and even | Function to find maximum and minimum value of a number that can be obtained by rotating bits ; Stores the value of N ; Stores the maximum value ; Stores the minimum value ; If temp is odd ; Update the maximum and the minimum value ; If flag is 1 , then return the maximum value ; Otherwise , return the maximum value ; Function to find the maximum difference between the sum of odd and even - indexed array elements possible by rotating bits ; Stores the maximum difference ; Stores the sum of elements present at odd indices ; Stores the sum of elements present at even indices ; Traverse the given array ; If the index is even ; Update the caseOne ; Stores the maximum difference ; Stores the sum of elements placed at odd positions ; Stores the sum of elements placed at even positions ; Traverse the array ; If the index is even ; Update the caseTwo ; Return the maximum of caseOne and caseTwo ; Driver Code
def Rotate ( n , f ) : NEW_LINE INDENT temp = n NEW_LINE maxi = n NEW_LINE mini = n NEW_LINE for idx in range ( 7 ) : NEW_LINE INDENT if temp & 1 : NEW_LINE INDENT temp >>= 1 NEW_LINE temp += 2 ** 7 NEW_LINE DEDENT else : NEW_LINE INDENT temp >>= 1 NEW_LINE DEDENT mini = min ( mini , temp ) NEW_LINE maxi = max ( maxi , temp ) NEW_LINE DEDENT if ( f ) : NEW_LINE INDENT return ( maxi ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( mini ) NEW_LINE DEDENT DEDENT def calcMinDiff ( arr ) : NEW_LINE INDENT caseOne = 0 NEW_LINE sumOfodd = 0 NEW_LINE sumOfeven = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if i % 2 : NEW_LINE INDENT sumOfodd += Rotate ( arr [ i ] , 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT sumOfeven += Rotate ( arr [ i ] , 1 ) NEW_LINE DEDENT DEDENT caseOne = abs ( sumOfodd - sumOfeven ) NEW_LINE caseTwo = 0 NEW_LINE sumOfodd = 0 NEW_LINE sumOfeven = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if i % 2 : NEW_LINE INDENT sumOfodd += Rotate ( arr [ i ] , 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT sumOfeven += Rotate ( arr [ i ] , 0 ) NEW_LINE DEDENT DEDENT caseTwo = abs ( sumOfodd - sumOfeven ) NEW_LINE return max ( caseOne , caseTwo ) NEW_LINE DEDENT arr = [ 123 , 86 , 234 , 189 ] NEW_LINE print ( calcMinDiff ( arr ) ) NEW_LINE