Longest Nice Subarray LeetCode Solution

Problem – Longest Nice Subarray LeetCode Solution

You are given an array nums consisting of positive integers.

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

Return the length of the longest nice subarray.

subarray is a contiguous part of an array.

Note that subarrays of length 1 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:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109

Longest Nice Subarray LeetCode Solution in Java

    public int longestNiceSubarray(int[] A) {
        int AND = 0, i = 0, res = 0, n = A.length;
        for (int j = 0; j < n; ++j) {
            while ((AND & A[j]) > 0)
                AND ^= A[i++];
            AND |= A[j];
            res = Math.max(res, j - i + 1);
        }
        return res;
    }

Longest Nice Subarray LeetCode Solution in C++

    int longestNiceSubarray(vector<int>& A) {
        int AND = 0, i = 0, res = 0, n = A.size();
        for (int j = 0; j < n; ++j) {
            while ((AND & A[j]) > 0)
                AND ^= A[i++];
            AND |= A[j];
            res = max(res, j - i + 1);
        }
        return res;
    }

Longest Nice Subarray LeetCode Solution in Python

    def longestNiceSubarray(self, A):
        res = AND = i = 0
        for j in range(len(A)):
            while AND & A[j]:
                AND ^= A[i]
                i += 1
            AND |= A[j]
            res = max(res, j - i + 1)
        return res
Longest Nice Subarray LeetCode Solution Review:

In our experience, we suggest you solve this Longest Nice Subarray LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Longest Nice Subarray LeetCode Solution

Find on Leetcode

Conclusion:

I hope this Longest Nice Subarray LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published.