Skip to content

Commit f8d116f

Browse files
committed
* File(s) Modified: 1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.cpp
* Language(s) Used: C++ * Submission URL: https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/submissions/959480145/
1 parent 0cc7ed4 commit f8d116f

1 file changed

+30
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
Using Sliding window.
3+
First we calculate sum of first k elements in vector then we check if the average is greater than or equal to the threshold.
4+
If the condition is met then we append the res variable.
5+
Then we maintain the k size window and traverse over the vector and check for the condition.
6+
7+
Since we are traversing only once
8+
T.C -> O(N)
9+
S.c -> O(1)
10+
*/
11+
class Solution {
12+
public:
13+
int numOfSubarrays(vector<int>& arr, int k, int threshold) {
14+
int sum = 0;
15+
int n = arr.size();
16+
for(int i=0;i<k;i++){
17+
sum += arr[i];
18+
}
19+
int left = 0;
20+
int right = k;
21+
int res = 0;
22+
if(sum/k >= threshold) res++;
23+
while(right < n){
24+
sum -= arr[left++];
25+
sum += arr[right++];
26+
if(sum/k >= threshold) res++;
27+
}
28+
return res;
29+
}
30+
};

0 commit comments

Comments
 (0)