Longest Subarray With Maximum Bitwise AND
The maximum AND equals the array's max — find the longest consecutive run of that value.
3 min read
bit-manipulation array
Problem#
Return the length of the longest subarray whose bitwise AND equals the maximum bitwise AND achievable over any subarray of nums.
Examples#
[1,2,3,3,2,2]→2(the two consecutive 3s).[1,2,3,4]→1.
Constraints#
1 <= nums.length <= 10^5,1 <= nums[i] <= 10^6.
Approach#
ANDing with any value < max strictly reduces the result, so the optimal AND equals the array maximum. The answer is the longest streak of consecutive elements equal to that max.
Solution#
class Solution {public: int longestSubarray(vector<int>& nums) { int mx = *max_element(nums.begin(), nums.end()); int ans = 0, run = 0; for (int v : nums) { if (v == mx) ans = max(ans, ++run); else run = 0; } return ans; }};func longestSubarray(nums []int) int { mx := nums[0] for _, v := range nums { if v > mx { mx = v } } ans, run := 0, 0 for _, v := range nums { if v == mx { run++ if run > ans { ans = run } } else { run = 0 } } return ans}from typing import List
class Solution: def longestSubarray(self, nums: List[int]) -> int: mx = max(nums) ans = 0 run = 0 for v in nums: if v == mx: run += 1 if run > ans: ans = run else: run = 0 return ansfunction longestSubarray(nums) { const mx = Math.max(...nums); let ans = 0, run = 0; for (const v of nums) { if (v === mx) { run++; if (run > ans) ans = run; } else { run = 0; } } return ans;}class Solution { public int longestSubarray(int[] nums) { int mx = nums[0]; for (int v : nums) if (v > mx) mx = v; int ans = 0, run = 0; for (int v : nums) { if (v == mx) { run++; if (run > ans) ans = run; } else { run = 0; } } return ans; }}function longestSubarray(nums: number[]): number { const mx = Math.max(...nums); let ans = 0, run = 0; for (const v of nums) { if (v === mx) { run++; if (run > ans) ans = run; } else { run = 0; } } return ans;}Editorial#
The key observation: AND is monotonic — adding more values to the AND can only clear bits, never set them. So the largest achievable AND is the largest single element, and to “achieve” it across a subarray, every value must equal it.
Complexity#
- Time:
O(n). - Space:
O(1).
Concept revision#
Related#