Skip to content

Commit 55cdff2

Browse files
committed
Time: 1349 ms (11.89%), Space: 31.2 MB (85.98%) - LeetHub
1 parent 2357d82 commit 55cdff2

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution:
2+
def longestNiceSubarray(self, nums: list[int]) -> int:
3+
# Binary search for the longest nice subarray length
4+
left, right = 0, len(nums)
5+
result = (1)
6+
7+
while left <= right:
8+
length = left + (right - left) // 2
9+
if self._can_form_nice_subarray(length, nums):
10+
result = length
11+
left = length + 1
12+
else:
13+
right = length - 1
14+
15+
return result
16+
def _can_form_nice_subarray(self, length: int, nums: list[int]) -> bool:
17+
if length <= 1:
18+
return True
19+
20+
for start in range(len(nums) - length + 1):
21+
bit_mask = 0
22+
is_nice = True
23+
24+
for pos in range(start, start + length):
25+
26+
if bit_mask & nums[pos] != 0:
27+
is_nice = False
28+
break
29+
bit_mask |= nums[pos]
30+
31+
if is_nice:
32+
return True
33+
34+
return False

0 commit comments

Comments
 (0)