Skip to content

2419. Longest Subarray With Maximum Bitwise AND 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int longestSubarray(vector<int>& nums) {
    int ans = 0;
    int maxIndex = 0;
    int sameNumLength = 0;

    for (int i = 0; i < nums.size(); ++i)
      if (nums[i] == nums[maxIndex]) {
        ans = max(ans, ++sameNumLength);
      } else if (nums[i] > nums[maxIndex]) {
        maxIndex = i;
        sameNumLength = 1;
        ans = 1;
      } else {
        sameNumLength = 0;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int longestSubarray(int[] nums) {
    int ans = 0;
    int maxIndex = 0;
    int sameNumLength = 0;

    for (int i = 0; i < nums.length; ++i)
      if (nums[i] == nums[maxIndex]) {
        ans = Math.max(ans, ++sameNumLength);
      } else if (nums[i] > nums[maxIndex]) {
        maxIndex = i;
        sameNumLength = 1;
        ans = 1;
      } else {
        sameNumLength = 0;
      }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def longestSubarray(self, nums: list[int]) -> int:
    ans = 0
    maxIndex = 0
    sameNumLength = 0

    for i, num in enumerate(nums):
      if nums[i] == nums[maxIndex]:
        sameNumLength += 1
        ans = max(ans, sameNumLength)
      elif nums[i] > nums[maxIndex]:
        maxIndex = i
        sameNumLength = 1
        ans = 1
      else:
        sameNumLength = 0

    return ans