Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Print pair with maximum AND value in an array in C Program.
In this problem, we are given an array of n positive integers and need to find a pair with the maximum AND value. The bitwise AND operation combines bits where both operands have 1 in the same position.
Syntax
int maxAND(int arr[], int n); int checkBit(int pattern, int arr[], int n);
Algorithm Approach
The algorithm works by building the maximum AND value bit by bit from the most significant bit (MSB) to the least significant bit (LSB). For each bit position, it checks if at least two numbers in the array have that bit set −
- checkBit() function counts how many numbers match a given bit pattern
- maxAND() function iterates through all 32 bits and builds the maximum AND value
- Finally, it finds and prints the actual pair that produces this maximum AND value
Example
#include <stdio.h>
int checkBit(int pattern, int arr[], int n) {
int count = 0;
for (int i = 0; i < n; i++)
if ((pattern & arr[i]) == pattern)
count++;
return count;
}
int maxAND(int arr[], int n) {
int res = 0, count;
/* Build maximum AND value bit by bit */
for (int bit = 31; bit >= 0; bit--) {
count = checkBit(res | (1 << bit), arr, n);
if (count >= 2)
res |= (1 << bit);
}
if (res == 0) {
printf("No possible AND pair<br>");
} else {
printf("Pair with maximum AND: ");
count = 0;
for (int i = 0; i < n && count < 2; i++) {
if ((arr[i] & res) == res) {
count++;
printf("%d ", arr[i]);
}
}
printf("<br>");
}
return res;
}
int main() {
int arr[] = {4, 8, 12, 16};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("<br>");
int result = maxAND(arr, n);
printf("Maximum AND value: %d<br>", result);
return 0;
}
Array: 4 8 12 16 Pair with maximum AND: 8 12 Maximum AND value: 8
How It Works
For the array {4, 8, 12, 16} with binary representations −
| Number | Binary |
|---|---|
| 4 | 0100 |
| 8 | 1000 |
| 12 | 1100 |
| 16 | 10000 |
The algorithm finds that 8 AND 12 = 8 (1000 AND 1100 = 1000), which is the maximum possible AND value.
Key Points
- Time complexity is O(32 * n) which simplifies to O(n)
- The algorithm processes bits from MSB to LSB to maximize the result
- If no valid pair exists, the maximum AND value will be 0
Conclusion
This bit manipulation approach efficiently finds the pair with maximum AND value by building the result bit by bit. It ensures we get the optimal solution in linear time complexity.
