Longest Subarray With Maximum Bitwise AND - Problem
You are given an integer array nums of size n.
Consider a non-empty subarray from nums that has the maximum possible bitwise AND.
- In other words, let
kbe the maximum value of the bitwise AND of any subarray ofnums. Then, only subarrays with a bitwise AND equal tokshould be considered.
Return the length of the longest such subarray.
The bitwise AND of an array is the bitwise AND of all the numbers in it.
A subarray is a contiguous sequence of elements within an array.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,3,3,2,1]
›
Output:
2
💡 Note:
The maximum bitwise AND is 3 (from element 3). The longest subarray with AND equal to 3 is [3,3] with length 2.
Example 2 — Single Element
$
Input:
nums = [1,2,3,4]
›
Output:
1
💡 Note:
Maximum element is 4. The longest subarray with maximum AND is [4] with length 1.
Example 3 — All Same Elements
$
Input:
nums = [5,5,5,5]
›
Output:
4
💡 Note:
All elements are 5, so the entire array has AND value 5. Length is 4.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Given array with various integer elements
2
Key Insight
Maximum AND equals maximum element value
3
Find Sequence
Locate longest consecutive sequence of max element
Key Takeaway
🎯 Key Insight: Maximum bitwise AND of any subarray equals the maximum array element - find longest consecutive sequence of max element
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code