File tree 1 file changed +35
-0
lines changed
scripts/algorithms/S/Smallest Subarrays With Maximum Bitwise OR
1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def smallestSubarrays (self , nums : List [int ]) -> List [int ]:
3
+ # two sweeps
4
+ len_n = len (nums )
5
+ # sweep 1: find the maximum OR value at each index
6
+ max_or = [0 ] * len_n
7
+ idx , c_or = len_n - 1 , 0
8
+ while idx >= 0 :
9
+ c_or |= nums [idx ]
10
+ max_or [idx ] = c_or
11
+ idx -= 1
12
+
13
+ # sweep 2: starting from the last number, track the closest index for every bit
14
+ ans = [1 ] * len_n
15
+ bidx = [None ] * 32
16
+ idx = len_n - 1
17
+ while idx >= 0 :
18
+ i = 0
19
+ n = nums [idx ]
20
+ while n :
21
+ if n & 1 :
22
+ bidx [i ] = idx
23
+ i += 1
24
+ n >>= 1
25
+ mor = max_or [idx ]
26
+ max_dist , i = 1 , 0
27
+ while mor :
28
+ if mor & 1 :
29
+ max_dist = max (max_dist , bidx [i ] - idx + 1 )
30
+ i += 1
31
+ mor >>= 1
32
+ ans [idx ] = max_dist
33
+ idx -= 1
34
+
35
+ return ans
You can’t perform that action at this time.
0 commit comments