Skip to content
Related Articles

Related Articles

Maximize difference between odd and even indexed array elements by swapping unequal adjacent bits in their binary representations
  • Last Updated : 24 Feb, 2021

Given an array arr[] consisting of N positive integers, the task is to find the maximum absolute difference between the sum of the array elements placed at even and odd indices of the array by swapping unequal adjacent bits of in the binary representation of any array element any number of times.

Examples:

Input: arr[] = {5, 7, 3, 1, 8}
Output: 9
Explanation:
arr[0] = (5)10 = (101)2. Left shift bits to make arr[0] = (110)2 = (6)10
Therefore, the array arr[] modifies to {5, 7, 3, 1, 8}.
Therefore, the maximum absolute difference = (6 + 3 + 8) – (7 + 1) = 9.

Input: arr[] = {54, 32, 11, 23}
Output: 58
Explanation: 
Modify arr[0] to 60 by left shifting the last two set bits of arr[0] (= 54). Therefore, the array arr[] modifies to {60, 32, 11, 23}.
Modify arr[1] to 1 by right shifting all the set bits of arr[1] (= 32). Therefore, the array arr[] modifies to {60, 1, 11, 23}
Modify arr[2] to 14 by left shifting the last three set bits of arr[2] (= 11). Therefore, the array arr[] modifies to {60, 1, 14, 23}.
Modify arr[3] to 15 by right shifting all the set bits of arr[3] (= 23). Therefore, the array arr[] modifies to {60, 1, 14, 15}.
Therefore, the maximum absolute difference = (60 + 14) – (15 + 1) = 58.

Approach: The idea is to use the observation that any set bit can be moved to any other position. Follow the steps below to solve the problem:



  • Define a function, say maximize(), to maximize a number by shifting two unequal adjacent bits.
  • Define a function, say minimize(), to minimize a number by shifting two unequal adjacent bits.
  • Perform the following operations:
    • Initialize a variable, say ans, to store the minimized value.
    • To minimize a number, shift all the set bits to the right position and all the unset bits to the left position.
    • Traverse over the range [0, count of set bit – 1] and update ans as ans | 1. If i not equal to the count of set bits, then left shift ans by 1.
    • Return the value of ans.
  • First, find the difference obtained by maximizing the element placed at even indices and minimizing the elements placed at odd indices. Store it in a variable, say caseOne.
  • Now, find the difference obtained by minimizing the element placed at even indices and maximizing the elements placed at odd indices. Store it in a variable, say caseTwo.
  • After completing the above steps, print the maximum of caseOne and CaseTwo.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program for the above approach
#include<bits/stdc++.h>
using namespace std;
 
// Function to count total number
// of bits present in a number
int countBit(int n){
  return int(log2(n))+1;
}
 
// Function to count total
// set bits in a number
int countSetBit(int n){
 
  // Stores the count
  // of set bits
  int ans = 0;
 
  while(n > 0){
 
    ans += (n & 1);
 
    // Right shift by 1
    n >>= 1;
  }
 
  // Return the final count
  return ans;
}
 
 
// Function to find maximum number
// by shifting two unequal bits
int maximize(int n){
 
  // Count set bits in number n
  int bits = countBit(n);
  int setBits = countSetBit(n);
  int ans = 0;
 
  // Iterate the string bits
  for(int i = 0; i < bits; i++){
 
    if (i < setBits)
      ans |= 1;
    if(i != setBits - 1)
      ans <<= 1;
 
  }
  return ans;
}
 
 
// Function to find minimum number
// by shifting two unequal bits
int minimize(int n){
 
  int setBits = countSetBit(n);
  int ans = 0;
 
  // Iterate the set bit
  for (int i = 0; i < setBits; i++){
    ans |= 1;
    if (i != setBits - 1)
      ans <<= 1;
  }
  return ans;
}
 
// Function to find the maximum difference
int maxDiff(vector<int> arr){
 
  // Stores the maximum difference
  int caseOne = 0;
 
  // Stores the sum of elements
  // placed at odd positions
  int SumOfOdd = 0;
 
  // Stores the sum of elements
  // placed at even positions
  int SumOfeven = 0;
 
  // Traverse the array
  for(int i = 0; i < arr.size(); i++){
    if (i % 2)
      SumOfOdd += minimize(arr[i]);
 
    else
      SumOfeven += maximize(arr[i]);
  }
   
  // Update CaseOne
  caseOne = abs(SumOfOdd - SumOfeven);
 
  // Stores the maximum diffrence
  int caseTwo = 0;
 
  // Assign value O
  SumOfOdd = 0;
  SumOfeven = 0;
 
  // Traverse the array
  for(int i = 0; i < arr.size(); i++)
  {
    if (i % 2)
      SumOfOdd += maximize(arr[i]);
    else
      SumOfeven += minimize(arr[i]);
  }
  // Update caseTwo
  caseTwo = abs(SumOfOdd - SumOfeven);
 
  // Return maximum of caseOne and CaseTwo
  return max(caseOne, caseTwo);
 
}
 
 
// Drivers Code
int main()
{
  vector<int> arr{54, 32, 11, 23};
 
  // Function Call
  cout<<maxDiff(arr);
 
}
// This code is contributed by ipg2016107.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output: 

58

 

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :