Maximum set bit sum in array without considering adjacent elements in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] of integers. Our task is to create a program to calculate the Maximum set bit sum in array without considering adjacent elements in C++.

Problem description − Here, we have an array arr[]. We have to find the number of set bits for each number. Then, we will find the maximum set bit sum in adjacent elements of the array. i.e. maximum sum for a[i] + a[i+2] ….

Let’s take an example to understand the problem,

Input

arr[] = {1, 4, 6, 7}

Output

4

Explanation

Array with the element’s in binary form

arr[] = {01, 100, 101, 111}
Bit count array = {1, 1, 2, 3}

Alternate bit count,

arr[0] + arr[2] = 1 + 2 = 3
arr[1] + arr[3] = 1 + 3 = 4

Max sum = 4.

Solution Approach

To solve this problem, we will simply find the number of set bits in the number. And find the alternate pair that has the maximum count of set bits.

The max sum will be for an array starting with 0 or starting with 1. So, we just need to check the case of two of them.

Program to illustrate the working of our solution,

Example

 Live Demo

#include<iostream>
using namespace std;
int countSetBit(int n){
   int setBits = 0;
   while(n) {
      setBits++;
      n = n & (n - 1);
   }
   return setBits;
}
int findMaxBitAltSubArray(int arr[], int n){
   int EvenSum = countSetBit(arr[0]);
   int OddSum = 0;
   for (int i = 1; i < n; i++){
      if(i % 2 == 0){
         EvenSum += countSetBit(arr[i]);
      } else {
         OddSum += countSetBit(arr[i]);
      }
   }
   if(EvenSum >= OddSum){
      return EvenSum;
   }
   return OddSum;
}
int main() {
   int arr[] = {1, 4, 6, 7};
   int n = 4;
   cout<<"The maximum set bit sum in the array without considering adjacent elements is "<<findMaxBitAltSubArray(arr, n);
   return 0;
}

Output

The maximum set bit sum in the array without considering adjacent elements
is 4
raja
Published on 03-Jul-2020 11:30:35
Advertisements