Maximize difference between odd and even indexed array elements by swapping unequal adjacent bits in their binary representations | Python program for the above approach ; Function to count total number of bits present in a number ; Function to count total set bits in a number ; Stores the count of set bits ; Right shift by 1 ; Return the final count ; Function to find maximum number by shifting two unequal bits ; Count set bits in number n ; Iterate the string bits ; Function to find minimum number by shifting two unequal bits ; Iterate the set bit ; Function to find the maximum difference ; 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 ; Update CaseOne ; Stores the maximum difference ; Assign value O ; Traverse the array ; Update caseTwo ; Return maximum of caseOne and CaseTwo ; Drivers Code ; Function Call
import math NEW_LINE def countBit ( n ) : NEW_LINE INDENT return int ( math . log ( n , 2 ) ) + 1 NEW_LINE DEDENT def countSetBit ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE while n : NEW_LINE INDENT ans += n & 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def maximize ( n ) : NEW_LINE INDENT bits = countBit ( n ) NEW_LINE setBits = countSetBit ( n ) NEW_LINE ans = 0 NEW_LINE for i in range ( bits ) : NEW_LINE INDENT if i < setBits : NEW_LINE INDENT ans |= 1 NEW_LINE DEDENT if i != setBits - 1 : NEW_LINE INDENT ans <<= 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def minimize ( n ) : NEW_LINE INDENT setBits = countSetBit ( n ) NEW_LINE ans = 0 NEW_LINE for i in range ( setBits ) : NEW_LINE INDENT ans |= 1 NEW_LINE if i != setBits - 1 : NEW_LINE INDENT ans <<= 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def maxDiff ( 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 += minimize ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT SumOfeven += maximize ( arr [ i ] ) 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 += maximize ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT SumOfeven += minimize ( arr [ i ] ) NEW_LINE DEDENT DEDENT caseTwo = abs ( SumOfOdd - SumOfeven ) NEW_LINE return max ( caseOne , caseTwo ) NEW_LINE DEDENT arr = [ 54 , 32 , 11 , 23 ] NEW_LINE print ( maxDiff ( arr ) ) NEW_LINE