---
# System prepended metadata

title: LC 2401. Longest Nice Subarray
tags: [medium, leedcode, Sliding Window, c++]

---

# LC 2401. Longest Nice Subarray

### [Problem link](https://leetcode.com/problems/longest-nice-subarray/)

###### tags: `leedcode` `medium` `c++` `Sliding Window`

You are given an array <code>nums</code> consisting of  **positive**  integers.

We call a subarray of <code>nums</code>  **nice**  if the bitwise  **AND**  of every pair of elements that are in  **different**  positions in the subarray is equal to <code>0</code>.

Return the length of the  **longest**  nice subarray.

A  **subarray**  is a  **contiguous**  part of an array.

 **Note**  that subarrays of length <code>1</code> are always considered nice.

**Example 1:** 

```
Input: nums = [1,3,8,48,10]
Output: 3
Explanation: The longest nice subarray is [3,8,48]. This subarray satisfies the conditions:
- 3 AND 8 = 0.
- 3 AND 48 = 0.
- 8 AND 48 = 0.
It can be proven that no longer nice subarray can be obtained, so we return 3.
```

**Example 2:** 

```
Input: nums = [3,1,5,11,13]
Output: 1
Explanation: The length of the longest nice subarray is 1. Any subarray of length 1 can be chosen.
```

 **Constraints:** 

- <code>1 <= nums.length <= 10<sup>5</sup></code>
- <code>1 <= nums[i] <= 10<sup>9</sup></code>

## Solution 1 - Sliding Window
#### C++
```cpp=
class Solution {
public:
    int longestNiceSubarray(vector<int>& nums) {
        int cnt = 0;
        int ans = 0;
        int l = 0;
        for (int r = 0; r < nums.size(); r++) {
            while ((nums[r] & cnt) > 0) {
                cnt ^= nums[l];
                l++;
            }
            cnt |= nums[r];
            ans = max(ans, r - l + 1);
        }
        return ans;
    }
};
```

>### Complexity
>|             | Time Complexity | Space Complexity |
>| ----------- | --------------- | ---------------- |
>| Solution 1  | O(n)            | O(1)             |

## Note
x
