Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold LeetCode solution in JavaScript

1
var numOfSubarrays = function (arr, k, threshold) {
2
let total = 0;
3
let left = 0;
4
let right = k;
5
// get initial sum of numbers in first sub array range, by summing left -> right
6
let sum = arr.slice(left, right).reduce((a, b) => a + b, 0);
7
while (right <= arr.length) {
8
// move through the array as a sliding window
9
if (left > 0) {
10
// on each iteration of the loop, subtract the val that has fallen out of the window,
11
// and add the new value that has entered the window
12
sum -= arr[left - 1];
13
sum += arr[right - 1];
14
}
15
if (sum / k >= threshold) {
16
total++;
17
}
18
left++;
19
right++;
20
}
21
return total;
22
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0