[LeetCode] Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold

1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int numOfSubarrays(vector<int>& arr, int k, int threshold) {
long long sum = 1ll * k * threshold;
long long window = 0;
for(int i = 0; i < k; i++) {
window += arr[i];
}
int res = window >= sum;
for(int i = k; i < arr.size(); i++) {
window += arr[i] - arr[i-k];
res += window >= sum;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/22/PS/LeetCode/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.