Maximize difference between odd and even indexed array elements by swapping unequal adjacent bits in their binary representations | 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
function countBit ( n ) { return parseInt ( log2 ( n ) ) + 1 ; } function countSetBit ( n ) { let ans = 0 ; while ( n > 0 ) { ans += ( n & 1 ) ; n >>= 1 ; } return ans ; } function maximize ( n ) { let bits = countBit ( n ) ; let setBits = countSetBit ( n ) ; let ans = 0 ; for ( let i = 0 ; i < bits ; i ++ ) { if ( i < setBits ) ans |= 1 ; if ( i != setBits - 1 ) ans <<= 1 ; } return ans ; } function minimize ( n ) { let setBits = countSetBit ( n ) ; let ans = 0 ; for ( let i = 0 ; i < setBits ; i ++ ) { ans |= 1 ; if ( i != setBits - 1 ) ans <<= 1 ; } return ans ; } function maxDiff ( arr ) { let caseOne = 0 ; let SumOfOdd = 0 ; let SumOfeven = 0 ; for ( let i = 0 ; i < arr . length ; i ++ ) { if ( i % 2 ) SumOfOdd += minimize ( arr [ i ] ) ; else SumOfeven += maximize ( arr [ i ] ) ; } caseOne = Math . abs ( SumOfOdd - SumOfeven ) ; let caseTwo = 0 ; SumOfOdd = 0 ; SumOfeven = 0 ; for ( let i = 0 ; i < arr . length ; i ++ ) { if ( i % 2 ) SumOfOdd += maximize ( arr [ i ] ) ; else SumOfeven += minimize ( arr [ i ] ) ; } caseTwo = Math . abs ( SumOfOdd - SumOfeven ) ; return Math . max ( caseOne , caseTwo ) ; } let arr = [ 54 , 32 , 11 , 23 ] ; document . write ( maxDiff ( arr ) ) ;