Longest Subarray With Maximum Bitwise AND

medium bit manipulation array brainteaser

Problem

Let k be the maximum bitwise AND over every non-empty subarray of nums. Among all subarrays whose bitwise AND equals k, return the length of the longest one.

Key observation: ANDing two different values can only turn bits off, so a & b < max(a, b) whenever a ≠ b. Hence the best possible AND is simply k = max(nums), achieved by a single element. The answer is the longest run of consecutive elements all equal to max(nums).

Inputnums = [1, 2, 3, 3, 2, 2]
Output2
The maximum AND is 3. The longest run of 3's is [3, 3], so the answer is 2.

def longestSubarray(nums):
    mx = max(nums)        # best AND equals the largest element
    best = 0              # longest valid run so far
    cur = 0               # length of current run of mx
    for v in nums:
        if v == mx:
            cur += 1
            best = max(best, cur)
        else:
            cur = 0       # run broken, reset
    return best
function longestSubarray(nums) {
  const mx = Math.max(...nums); // best AND equals the largest element
  let best = 0;                 // longest valid run so far
  let cur = 0;                  // length of current run of mx
  for (const v of nums) {
    if (v === mx) {
      cur += 1;
      best = Math.max(best, cur);
    } else {
      cur = 0;                  // run broken, reset
    }
  }
  return best;
}
int longestSubarray(int[] nums) {
    int mx = 0;                 // best AND equals the largest element
    for (int v : nums) mx = Math.max(mx, v);
    int best = 0;               // longest valid run so far
    int cur = 0;                // length of current run of mx
    for (int v : nums) {
        if (v == mx) {
            cur++;
            best = Math.max(best, cur);
        } else {
            cur = 0;            // run broken, reset
        }
    }
    return best;
}
int longestSubarray(vector<int>& nums) {
    int mx = *max_element(nums.begin(), nums.end());
    int best = 0;               // longest valid run so far
    int cur = 0;                // length of current run of mx
    for (int v : nums) {
        if (v == mx) {
            cur++;
            best = max(best, cur);
        } else {
            cur = 0;            // run broken, reset
        }
    }
    return best;
}
Time: O(n) Space: O(1)