LeetCode 2680: Maximum OR
Problem Description
Explanation
To solve this problem, we need to find the maximum possible value of the bitwise OR operation applied to the elements of the array after applying the multiplication operation at most k times. We can achieve this by iteratively selecting the element with the highest bit set at the position we are interested in increasing.
The algorithm involves finding the leftmost set bit in each element of the array. We then iterate over k times, each time selecting the element that has the highest leftmost set bit. We double that element by multiplying it by 2 and update the leftmost set bit position. Finally, we calculate the bitwise OR of all elements to get the maximum possible value.
- Time complexity: O(nk) where n is the length of the array and k is the maximum number of operations allowed.
- Space complexity: O(1)
Solutions
class Solution {
public int maximumOr(int[] nums, int k) {
int res = 0;
for (int i = 30; i >= 0; i--) {
int mask = 1 << i;
int count = 0;
for (int num : nums) {
if ((num & mask) == mask) {
count++;
}
}
if (count > 0) {
if (k > 0) {
int maxCount = Math.min(count, k);
res |= mask;
k -= maxCount;
} else {
res |= mask;
}
}
}
return res;
}
}
Loading editor...