2411. Smallest Subarrays With Maximum Bitwise OR #1984
-
|
Topics: You are given a 0-indexed array
The bitwise OR of an array is the bitwise OR of all the numbers in it. Return an integer array A subarray is a contiguous non-empty sequence of elements within an array. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to find, for each starting index Approach
Let's implement this solution in PHP: 2411. Smallest Subarrays With Maximum Bitwise OR <?php
/**
* @param Integer[] $nums
* @return Integer[]
*/
function smallestSubarrays($nums) {
$n = count($nums);
$ans = array_fill(0, $n, 0);
$next_occurrence = array_fill(0, 32, -1);
$curOR = 0;
for ($i = $n - 1; $i >= 0; $i--) {
$num = $nums[$i];
for ($b = 0; $b < 32; $b++) {
if ($num & (1 << $b)) {
$next_occurrence[$b] = $i;
}
}
$curOR |= $num;
$max_j = $i;
for ($b = 0; $b < 32; $b++) {
if ($curOR & (1 << $b)) {
if ($next_occurrence[$b] > $max_j) {
$max_j = $next_occurrence[$b];
}
}
}
$ans[$i] = $max_j - $i + 1;
}
return $ans;
}
// Test cases
// Example 1:
$nums = [1, 0, 2, 1, 3];
print_r(smallestSubarrays($nums)); // Output: [3,3,2,2,1]
// Example 2:
$nums = [1, 2];
print_r(smallestSubarrays($nums)); // Output: [2,1]
?>Explanation:
This approach efficiently computes the desired result by leveraging bit manipulation and a backward pass through the array, ensuring optimal performance even for large input sizes. |
Beta Was this translation helpful? Give feedback.
We need to find, for each starting index
iin the given array, the smallest subarray starting atithat achieves the maximum possible bitwise OR for any subarray starting ati. The bitwise OR of a subarray is the bitwise OR of all elements in that subarray. The challenge is to efficiently compute this for each index in the array.Approach
Problem Analysis: The key observation is that the maximum bitwise OR for any subarray starting at index
iis the bitwise OR of the entire subarray fromito the end of the array. This is because the bitwise OR operation is monotonic; adding more elements can only set more bits, never unset them. Therefore, the maximum OR value for subarrays starting ati…