We are given an array of integers, arr
, and an integer k
. The task is to find the K-or of the array. The K-or of the array is defined as the maximum bitwise OR value of any k elements from the array.
arr
?
k
?
k
is an integer where (1 \leq k \leq \text{size of the array}).k
is 1?
k
is 1, the function should return the maximum value of the array since picking one element will yield its own value as the OR result.#include <iostream>
#include <vector>
#include <algorithm>
int findKOrOfArray(const std::vector<int>& arr, int k) {
int n = arr.size();
if (k == 1) {
return *std::max_element(arr.begin(), arr.end());
}
int max_or = 0;
for (int bit = 31; bit >= 0; --bit) {
std::vector<int> candidates;
for (int num : arr) {
if (num & (1 << bit)) {
candidates.push_back(num);
}
}
if (candidates.size() >= k) {
max_or |= (1 << bit);
arr = std::move(candidates);
}
}
return max_or;
}
int main() {
std::vector<int> arr = {3, 6, 9, 5};
int k = 2;
std::cout << "The K-or of the array is: " << findKOrOfArray(arr, k) << std::endl;
return 0;
}
k
equals 1, return the maximum element since OR’ing one number results in the number itself.k
, update the max_or
to include this bit and continue with the filtered list of elements.Thus, the overall time complexity is O(n) where n
is the number of elements in the array. This is efficient enough for large arrays up to the order of (10^5).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?