Longest Subarray With Maximum Bitwise AND Problem
#2419
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2419.
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.
Example 1:
Input: nums = [1,2,3,3,2,2]
Output: 2
Explanation:
The maximum possible bitwise AND of a subarray is 3.
The longest subarray with that value is [3,3], so we return 2.
Example 2:
Input: nums = [1,2,3,4]
Output: 1
Explanation:
The maximum possible bitwise AND of a subarray is 4.
The longest subarray with that value is [4], so we return 1.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^6
Solution
Approach: Observation
AND never makes a number larger, so the maximum AND of any subarray equals the largest element mx, and a subarray reaches it only if every element equals mx. The task becomes finding the longest run of consecutive mx values.
Find mx, then scan once, counting the current run of mx and keeping the longest.
Complexity: O(n) time and O(1) extra space.
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
mx = max(nums)
ans = cnt = 0
for x in nums:
if x == mx:
cnt += 1
ans = max(ans, cnt)
else:
cnt = 0
return ans