- Related Questions & Answers
- Maximum sum of difference of adjacent elements in C++
- Maximum sum such that no two elements are adjacent - Set 2 in C++
- Maximum sum in circular array such that no two elements are adjacent in C++
- Maximum sum such that no two elements are adjacent in C++
- Maximum decreasing adjacent elements in JavaScript
- Maximum sum such that no two elements are adjacent Alternate Method in C++ program
- Maximum product of 4 adjacent elements in matrix in C++
- Maximum sum in a 2 x n grid such that no two elements are adjacent in C++
- Adjacent elements of array whose sum is closest to 0 - JavaScript
- Maximum product of any two adjacent elements in JavaScript
- Maximum length subsequence with difference between adjacent elements as either 0 or 1 | Set 2 in C++
- Maximum triplet sum in array in C++
- Maximum sum from a tree with adjacent levels not allowed in C++
- Maximum Subarray Sum Excluding Certain Elements in C++
- Pair of (adjacent) elements of an array whose sum is lowest JavaScript

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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,**

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

4

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.

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,**

#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; }

The maximum set bit sum in the array without considering adjacent elements is 4

Advertisements