Show problems as
Classic problem #2401MediumArrayBit ManipulationSliding Window

Longest Nice Subarray

Real-world version: The Longest Run of Masks Sharing No Channel
Tracked in this browser only
Read Longest Nice Subarray on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A list of channel masks reads masks. Each mask is a positive whole number, and the bits of its binary form say which channels that mask claims.

A run of neighbouring masks is clean when no channel is claimed by two of its masks: for every pair in the run, no bit is set in both.

Return the length of the longest clean run. A run holding a single mask is always clean.

Examples

Example 1

Input
masks = [2, 4, 8, 3]
Output
3

The first three masks each claim a single channel of their own, so they form a clean run of three. The last mask claims the two lowest channels, which clashes with the first mask, but the last three masks are clean together as well, so three is the best either way.

Example 2

Input
masks = [7, 7, 7]
Output
1

All three masks claim the same channels, so no two of them sit in a run together and a single mask is the longest clean run.

Example 3

Input
masks = [1, 2, 4, 8, 16]
Output
5

Every mask claims a channel no other one touches, so the whole list is clean.

Constraints

  • 1 <= masks.length <= 10^5
  • 1 <= masks[i] <= 10^9

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def longest_nice_subarray(masks: list[int]) -> int:
Java
public int longestNiceSubarray(int[] masks)