Skip to content

Latest commit

 

History

History
114 lines (105 loc) · 4.5 KB

README.md

File metadata and controls

114 lines (105 loc) · 4.5 KB

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.

A 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

Companies: Paytm

Related Topics:
Array, Bit Manipulation, Sliding Window

Similar Questions:

Solution 1. Sliding Window

Use the shrinkable template.

// OJ: https://leetcode.com/problems/longest-nice-subarray
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    int longestNiceSubarray(vector<int>& A) {
        int cnt[32] = {}, i = 0, j = 0, N = A.size(), ans = 0;
        auto valid = [&]() {
            for (int k = 0; k < 32; ++k) {
                if (cnt[k] > 1) return false;
            }
            return true;
        };
        for (; j < N; ++j) {
            for (int k = 0; k < 32; ++k) {
                cnt[k] += (A[j] >> k & 1);
            }
            while (!valid()) {
                for (int k = 0; k < 32; ++k) {
                    cnt[k] -= (A[i] >> k & 1);
                }
                ++i;
            }
            ans = max(ans, j - i + 1);
        }
        return ans;
    }
};

Or use the non-shrinkable template:

// OJ: https://leetcode.com/problems/longest-nice-subarray
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    int longestNiceSubarray(vector<int>& A) {
        int cnt[32] = {}, i = 0, j = 0, N = A.size(), ans = 0;
        auto valid = [&]() {
            for (int k = 0; k < 32; ++k) {
                if (cnt[k] > 1) return false;
            }
            return true;
        };
        for (; j < N; ++j) {
            for (int k = 0; k < 32; ++k) {
                cnt[k] += (A[j] >> k & 1);
            }
            if (!valid()) {
                for (int k = 0; k < 32; ++k) {
                    cnt[k] -= (A[i] >> k & 1);
                }
                ++i;
            }
        }
        return j - i;
    }
};