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

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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 + arr = 1 + 2 = 3
arr + arr = 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);
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