All subarrays
For each subarray we can compute the Bitwise AND in time.
Time , space:
.
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
max_and = 0
max_len = 0
for i in range(len(nums)):
if nums[i] > max_and:
max_and = nums[i]
max_len = 1
elif nums[i] == max_and:
max_len = max(max_len, 1)
bitwise_and = nums[i]
for j in range(i+1, len(nums)):
bitwise_and &= nums[j]
if bitwise_and > max_and:
max_and = bitwise_and
max_len = j-i+1
elif bitwise_and == max_and:
max_len = max(max_len, j-i+1)
return max_len
Property of AND
Note, all numbers are positive. We can never increase a positive number by Bitwise ANDing with another number
, the best we can do is to keep
as it is and that happens when we have:
. So, the maximum Bitwise AND is the maximum number in
nums. From that point of view, we need to find the longest contiguous sequence of the maximum number. We use sliding window.
Time: , space:
.
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
max_len = 0
max_num = float("-inf")
begin = 0
for end, x in enumerate(nums):
if x > max_num:
max_num = x
begin = end
max_len = 1
continue
if x < max_num:
max_len = max(max_len, end-begin)
begin = end+1
# Since the last begin, all numbers might have been
# max, so we include that stretch.
return max(max_len, len(nums)-begin)
Leave a comment