Find the longest contiguous segment whose bitwise AND is as large as possible.
Given an integer array, consider the bitwise AND of every contiguous subarray. Your task is to find the maximum possible bitwise AND value among all subarrays, then return the length of the longest contiguous subarray that achieves that maximum value.
A key observation is that the bitwise AND of any subarray cannot exceed the largest element in the array, and the best possible value is determined by the maximum element itself. The problem reduces to locating the longest consecutive run of that maximum value.
Input Format
- An integer array
numsof lengthn. - Each element is a non-negative integer.
Output Format
- Return the length of the longest contiguous subarray whose bitwise AND is maximum among all contiguous subarrays.
Constraints
1 <= n <= $10^{5}$0 <= nums[i] <= $10^{9}$- The answer always fits in a 32-bit signed integer.
Example 1
Input
nums = [1,2,3,3,2,2]
Output
2
Explanation
The maximum possible bitwise AND over any contiguous subarray is 3, achieved by subarrays containing only 3. The longest such contiguous subarray is [3, 3], so the answer is 2.
Example 2
Input
nums = [5,5,5]
Output
3
Explanation
The maximum bitwise AND is 5, and the entire array already has that value.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.