Skip to content

Commit 249bc2e

Browse files
authored
Create number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.py
1 parent 691f7fe commit 249bc2e

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
import itertools
5+
6+
7+
class Solution(object):
8+
def numOfSubarrays(self, arr, k, threshold):
9+
"""
10+
:type arr: List[int]
11+
:type k: int
12+
:type threshold: int
13+
:rtype: int
14+
"""
15+
result, curr = 0, sum(itertools.islice(arr, 0, k-1))
16+
for i in xrange(k-1, len(arr)):
17+
curr += arr[i]-(arr[i-k] if i-k >= 0 else 0)
18+
result += int(curr >= threshold*k)
19+
return result
20+
21+
22+
# Time: O(n)
23+
# Space: O(n)
24+
class Solution2(object):
25+
def numOfSubarrays(self, arr, k, threshold):
26+
"""
27+
:type arr: List[int]
28+
:type k: int
29+
:type threshold: int
30+
:rtype: int
31+
"""
32+
accu = [0]
33+
for x in arr:
34+
accu.append(accu[-1]+x)
35+
result = 0
36+
for i in xrange(len(accu)-k):
37+
if accu[i+k]-accu[i] >= threshold*k:
38+
result += 1
39+
return result

0 commit comments

Comments
 (0)