longest_subarray_with_maximum_bitwise_and

 1# @leet start
 2class Solution:
 3    def longestSubarray(self, nums: list[int]) -> int:
 4        """
 5        This question asks us to find the subarray with the maximum bitwise AND
 6        and return its length.
 7
 8        To find the maximum bitwise AND, we know we have at least one (the max
 9        number in the array). Then, we know that Bitwise ANDing successive numbers
10        only decreases or keeps the number the same. So we just want to count
11        the longest length of the max number.
12        """
13        max_val, ans, curr = max(nums), 0, 0
14
15        for num in nums:
16            if num == max_val:
17                curr += 1
18            else:
19                curr = 0
20            ans = max(ans, curr)
21        return ans
22
23
24# @leet end
25
26
27def test():
28    assert 2 + 2 == 4
class Solution:
 3class Solution:
 4    def longestSubarray(self, nums: list[int]) -> int:
 5        """
 6        This question asks us to find the subarray with the maximum bitwise AND
 7        and return its length.
 8
 9        To find the maximum bitwise AND, we know we have at least one (the max
10        number in the array). Then, we know that Bitwise ANDing successive numbers
11        only decreases or keeps the number the same. So we just want to count
12        the longest length of the max number.
13        """
14        max_val, ans, curr = max(nums), 0, 0
15
16        for num in nums:
17            if num == max_val:
18                curr += 1
19            else:
20                curr = 0
21            ans = max(ans, curr)
22        return ans
def longestSubarray(self, nums: list[int]) -> int:
 4    def longestSubarray(self, nums: list[int]) -> int:
 5        """
 6        This question asks us to find the subarray with the maximum bitwise AND
 7        and return its length.
 8
 9        To find the maximum bitwise AND, we know we have at least one (the max
10        number in the array). Then, we know that Bitwise ANDing successive numbers
11        only decreases or keeps the number the same. So we just want to count
12        the longest length of the max number.
13        """
14        max_val, ans, curr = max(nums), 0, 0
15
16        for num in nums:
17            if num == max_val:
18                curr += 1
19            else:
20                curr = 0
21            ans = max(ans, curr)
22        return ans

This question asks us to find the subarray with the maximum bitwise AND and return its length.

To find the maximum bitwise AND, we know we have at least one (the max number in the array). Then, we know that Bitwise ANDing successive numbers only decreases or keeps the number the same. So we just want to count the longest length of the max number.

def test():
28def test():
29    assert 2 + 2 == 4