[LeetCode] Longest Subarray With Maximum Bitwise AND

2419. Longest Subarray With Maximum Bitwise AND

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 k be the maximum value of the bitwise AND of any subarray of nums. Then, only subarrays with a bitwise AND equal to k should 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int longestSubarray(vector<int>& A) {
int ma = *max_element(begin(A), end(A));
int l = 0, r = 0, n = A.size(), res = 0;
while(r < n) {
while(r < n and A[l] == A[r]) r++;
if(A[l] == ma) res = max(res, r - l);
l = r;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/10/PS/LeetCode/longest-subarray-with-maximum-bitwise-and/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.