Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit f40b478

Browse files
authoredNov 3, 2019
Create count-number-of-nice-subarrays.py
1 parent 349d1d0 commit f40b478

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
 
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Time: O(n)
2+
# Space: O(k)
3+
4+
class Solution(object):
5+
def numberOfSubarrays(self, nums, k):
6+
"""
7+
:type nums: List[int]
8+
:type k: int
9+
:rtype: int
10+
"""
11+
def atMost(nums, k):
12+
result, left, count = 0, 0, 0
13+
for right in xrange(len(nums)):
14+
count += nums[right]%2
15+
while count > k:
16+
count -= nums[left]%2
17+
left += 1
18+
result += right-left+1
19+
return result
20+
21+
return atMost(nums, k) - atMost(nums, k-1)
22+
23+
24+
# Time: O(n)
25+
# Space: O(k)
26+
import collections
27+
28+
29+
class Solution2(object):
30+
def numberOfSubarrays(self, nums, k):
31+
"""
32+
:type nums: List[int]
33+
:type k: int
34+
:rtype: int
35+
"""
36+
result = 0
37+
dq = collections.deque([-1])
38+
for i in xrange(len(nums)):
39+
if nums[i]%2:
40+
dq.append(i)
41+
if len(dq) > k+1:
42+
dq.popleft()
43+
if len(dq) == k+1:
44+
result += dq[1]-dq[0]
45+
return result

0 commit comments

Comments
 (0)
Please sign in to comment.