Minimize Array Sum by replacing pairs with (X, Y) keeping their bitwise OR same
Given an array arr[] of size N. Find the minimum sum of the array after performing given operations any number of times:
- Select two different indices i, j (1 ≤ i < j ≤ N),
- Replace arr[i] and arr[j] with X and Y respectively (X, Y>0), such that arr[i] | arr[j] = X | Y, where | denotes the bitwise OR operation
Examples:
Input: arr[] = {1, 3, 2}
Output: 3
Explanation: arr = {1, 3, 2} {bitwise OR of array elements is 3.}, sum=6
Replace 1 and 3 with 3 and 0 as {1|3 = 3 = 3|0}.
arr = {3, 0, 2}, {bitwise OR of array elements is still 3}, sum = 5
Replace 3 and 2 with 3 and 0 as {3|2 = 3 = 3|0}
arr = {3, 0, 0} {or of all array elements is still 3), sum= 3.
This is the minimum sum possible.Input: arr[] = {3, 5, 6}
Output: 7
Approach: The solution to the problem is based on the following observation:
If (arr[i], arr[j]) is replaced with ((arr[i] | arr[j]), 0), the bitwise OR value will remain the same and the sum will be minimized.
Illustration:
Consider: arr[] = {1, 3, 2}
Initial Array sum = 6
Operation 1: Replace (1, 3) with (1|3 , 0):
-> Bitwise OR of (1, 3) = 3
-> Replacing 1 with bitwise OR value 3 and 3 with 0 respectively
-> New pair will be (3, 0), whose bitwise OR value will be 3|0 = 3 (same as original pair (1, 3)).
-> Updated Array: {3, 0, 2}
-> Updated Array sum = 5Operation 2: Similarly replace (3, 2) with (3|2 , 0):
-> Bitwise OR of (3, 2) = 3
-> Replacing 3 with bitwise OR value 3 and 2 with 0 respectively
-> New pair will be (3, 0), whose bitwise OR value will be 3|0 = 3 (same as original pair (3, 2)).
-> Updated Array: {3, 0, 0}
-> Updated Array sum = 3Now no more operations can be done and the Array sum cannot be reduced further from 3.
Therefore final minimized Array sum will be the bitwise OR of all Array elements.
Follow the steps mentioned below:
- Traverse the array from the starting.
- Calculate the bitwise OR of all the array elements.
- Return this as the answer.
Below is the implementation of the above approach,
C++
// C++ code to implement the approach #include <bits/stdc++.h>using namespace std;typedef long long int ll; // Function minsum() which will calculate// the minimum sum of the given arrayll minsum(ll array[], ll n, ll sum){ for (int i = 0; i < n; i++) { // Calculating the or of // all the elements in the array sum |= array[i]; } return sum;} // Driver codeint main(){ ll array[] = { 1, 3, 2 }; // Calculating the size of array ll n = sizeof(array) / sizeof(array[0]); // Initialising a variable sum with zero ll sum = 0; // Function call cout << minsum(array, n, sum) << "\n"; return 0;} |
31
Time Complexity: O(N)
Auxiliary Space: O(1)

