Intuition¶
- Max Bitwise AND: The maximum bitwise AND will always involve the largest number in the array (or numbers equal to it), since any bitwise AND operation with a smaller number will result in a smaller or equal value.
- Longest Subarray: Once we find the maximum element in the array, we need to find the longest contiguous subarray consisting only of this element to ensure the bitwise AND remains maximum.
Approach¶
- Traverse the array and keep track of the maximum element seen so far (
currMax). - If we find an element larger than
currMax, updatecurrMax, reset the size of the current subarray to 1, and reset the result. - If we find another element equal to
currMax, increase the size of the subarray and update the result to reflect the longest subarray of the maximum element. - If the element is smaller than
currMax, reset the size to 0 since the subarray is broken. - Return the result at the end of the traversal.
Complexity¶
-
Time complexity:
The solution involves a single pass over the array, so the time complexity is $O(n)$ wherenis the number of elements in the input array. -
Space complexity:
The space complexity is $O(1)$ because only a few integer variables are used for tracking state.