- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum bitwise AND value of a pair in an array in C++
Problem statement
Given an array of n positive elements. we need to find the maximum bitwise AND value generated by any pair of element from the array.
Example
If input array is {10, 12, 15, 18} then maximum value of bitwise AND is 12.
Algorithm
The result of bitwise AND operations on single bit is maximum when both bits are 1. Considering this property −
- Start from the MSB and check whether we have minimum of two elements of array having set value
- If yes, then that MSB will be part of our solution and be added to result otherwise we will discard that bit
- Similarly, iterating from MSB to LSB (32 to 1) for bit position we can easily check which bit will be part of our solution and will keep adding all such bits to our solution
Example
Let us now see an example −
#include <bits/stdc++.h> using namespace std; int checkBits(int *arr, int n, int pattern) { int cnt = 0; for (int i = 0; i < n; ++i) { if ((pattern & arr[i]) == pattern) { ++cnt; } } return cnt; } int getMaxBitwiseAnd(int *arr, int n) { int result = 0; int count; for (int i = 31; i >= 0; --i) { count = checkBits(arr, n, result | (1 << i)); if (count >= 2) { result |= (1 << i); } } return result; } int main() { int arr[] = {10, 12, 15, 18}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum bitwise AND = " << getMaxBitwiseAnd(arr, n) << endl; return 0; }
Output
Maximum bitwise AND = 12
- Related Articles
- Print pair with maximum AND value in an array in C Program.
- Maximum Bitwise AND pair from given range in C++
- Find pair with maximum GCD in an array in C++
- Find a pair from the given array with maximum nCr value in C++
- Maximum XOR value of a pair from a range in C++
- Find a pair with maximum product in array of Integers in C++
- Maximize the bitwise OR of an array in C++
- Find a pair from the given array with maximum nCr value in Python
- Maximum value of XOR among all triplets of an array in C++
- Find subsequences with maximum Bitwise AND and Bitwise OR in Python
- Maximum value in an array after m range increment operations in C++
- Probability of a random pair being the maximum weighted pair in C++
- Function that returns the minimum and maximum value of an array in JavaScript
- Bitwise AND of sub-array closest to K in C++
- Maximum Length of Pair Chain in C++

Advertisements