Advertisement
2401. Longest Nice Subarray
MediumView on LeetCode
Time: O(n)
Space: O(1)
Approach
Sliding window with bitmask; shrink left when new element shares bits with window.
2401.cs
C#
// Approach: Sliding window with bitmask; shrink left when new element shares bits with window.
// Time: O(n) Space: O(1)
public 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;
}
}Advertisement
Was this solution helpful?