Given an array of integers
Output: 3
Explanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively.
All other sub-arrays of size 3 have averages less than 4 (the threshold).
Output: 6
Explanation: The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.
Constraints:
1 <= arr.length <= 105 1 <= nums[i] <= 104 0 <= k <= arr.length 0 <= threshold <= 104
Contents
Solution 1 - Using sliding window technique, take the moving sum of window size of K and check if the average is greater than or equal to threshold
In this approach, we are going to apply sliding window technique, using two pointers
Implementation steps:
-
First, we will create four variables
left ,right that we will use to adjust the window,result to hold the result, andmovingSum to track the sum of current window'sk elements. -
Next, run a
while loop untilright pointer reaches end of array, and check:-
If the difference between right and left pointers are greater than K-1: This means that we are going out of window size
k (since array is 0-indexed we are taking k-1 here), so check if the averagemovingSum/k is greater than or equal tothreshold , if it is then we have found a subarray, so incrementresult . Then, subtractarr[left] frommovingSum since we are going to move to next window, and incrementleft pointer by 1. -
Next, add current
right pointer value tomovingSum and incrementright pointer.
-
If the difference between right and left pointers are greater than K-1: This means that we are going out of window size
-
Finally, return the
result .
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(1).
Above implementations source code can be found at