File tree 1 file changed +34
-0
lines changed
2478-longest-nice-subarray
1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments