Maximize difference between odd and even indexed array elements by swapping unequal adjacent bits in their binary representations | CPP 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countBit ( int n ) { return int ( log2 ( n ) ) + 1 ; } int countSetBit ( int n ) { int ans = 0 ; while ( n > 0 ) { ans += ( n & 1 ) ; n >>= 1 ; } return ans ; } int maximize ( int n ) { int bits = countBit ( n ) ; int setBits = countSetBit ( n ) ; int ans = 0 ; for ( int i = 0 ; i < bits ; i ++ ) { if ( i < setBits ) ans |= 1 ; if ( i != setBits - 1 ) ans <<= 1 ; } return ans ; } int minimize ( int n ) { int setBits = countSetBit ( n ) ; int ans = 0 ; for ( int i = 0 ; i < setBits ; i ++ ) { ans |= 1 ; if ( i != setBits - 1 ) ans <<= 1 ; } return ans ; } int maxDiff ( vector < int > arr ) { int caseOne = 0 ; int SumOfOdd = 0 ; int SumOfeven = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { if ( i % 2 ) SumOfOdd += minimize ( arr [ i ] ) ; else SumOfeven += maximize ( arr [ i ] ) ; } caseOne = abs ( SumOfOdd - SumOfeven ) ; int caseTwo = 0 ; SumOfOdd = 0 ; SumOfeven = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { if ( i % 2 ) SumOfOdd += maximize ( arr [ i ] ) ; else SumOfeven += minimize ( arr [ i ] ) ; } caseTwo = abs ( SumOfOdd - SumOfeven ) ; return max ( caseOne , caseTwo ) ; } int main ( ) { vector < int > arr { 54 , 32 , 11 , 23 } ; cout << maxDiff ( arr ) ; }