LeetCode 1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold
Question
Given an array of integers arr
and two integers k
and threshold
.
Return the number of sub-arrays of size k
and average greater than or equal to threshold
.
Example
1 | Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4 |
Solution
It’s sliding window problem, and we just need to maintain the k size window and calculate the average. Also we can use one variable to store the sum that we add so far to reduce the duplicate calculations. In addtion, you can use prefix sum array to optimize.
Code
1 | // time:O(n - k + 1 ~ n) space:O(1) |