-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathcount-good-subarrays.py
More file actions
62 lines (55 loc) · 1.72 KB
/
count-good-subarrays.py
File metadata and controls
62 lines (55 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# Time: O(n)
# Space: O(n)
# combinatorics, mono stack
class Solution(object):
def countGoodSubarrays(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def is_proper_subset(a, b):
return a != b and a|b == b
def is_subset(a, b):
return a|b == b
right = [len(nums)]*len(nums)
stk = []
for i in reversed(xrange(len(nums))):
while stk and is_subset(nums[stk[-1]], nums[i]):
stk.pop()
right[i] = stk[-1] if stk else len(nums)
stk.append(i)
result, left = 0, -1
stk = []
for i in xrange(len(nums)):
while stk and is_proper_subset(nums[stk[-1]], nums[i]):
stk.pop()
left = stk[-1] if stk else -1
stk.append(i)
result += (i-left)*(right[i]-i)
return result
# Time: O(n)
# Space: O(n)
# combinatorics, mono stack
class Solution2(object):
def countGoodSubarrays(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def is_proper_subset(a, b):
return a != b and a|b == b
def is_subset(a, b):
return a|b == b
left = [-1]*len(nums)
stk = []
for i in reversed(xrange(len(nums))):
while stk and not is_proper_subset(nums[i], nums[stk[-1]]):
left[stk.pop()] = i
stk.append(i)
right = [len(nums)]*len(nums)
stk = []
for i in xrange(len(nums)):
while stk and not is_subset(nums[i], nums[stk[-1]]):
right[stk.pop()] = i
stk.append(i)
return sum((i-left[i])*(right[i]-i) for i in xrange(len(nums)))