Skip to content

2401. Longest Nice Subarray 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int longestNiceSubarray(vector<int>& nums) {
    int ans = 0;
    int used = 0;

    for (int l = 0, r = 0; r < nums.size(); ++r) {
      while (used & nums[r])
        used ^= nums[l++];
      used |= nums[r];
      ans = max(ans, r - l + 1);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int longestNiceSubarray(int[] nums) {
    int ans = 0;
    int used = 0;

    for (int l = 0, r = 0; r < nums.length; ++r) {
      while ((used & nums[r]) > 0)
        used ^= nums[l++];
      used |= nums[r];
      ans = Math.max(ans, r - l + 1);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def longestNiceSubarray(self, nums: list[int]) -> int:
    ans = 0
    used = 0

    l = 0
    for r, num in enumerate(nums):
      while used & num:
        used ^= nums[l]
        l += 1
      used |= num
      ans = max(ans, r - l + 1)

    return ans