[
accumulate
sliding window
]
Leetcode 1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold
Problem statement
Solution
Just use accumulate, then we can calculate sums in all n - k + 1
subarrays of size k
fast.
Complexity
It is O(n)
for time and space.
Code
class Solution:
def numOfSubarrays(self, arr, k, threshold):
acc = [0] + list(accumulate(arr))
return sum(acc[i + k] - acc[i] >= threshold * k for i in range(len(arr) - k + 1))