Skip to content

Commit 169a4e9

Browse files
authoredNov 8, 2024
Merge pull request #3690 from vermavarun/main
Create 1343-number-of-sub-arraysofSize-k-and-average-greaterthanor-equal-to-threshold.cs
2 parents 3060b48 + 0cdc715 commit 169a4e9

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
3+
Approach:
4+
1. We will initialize i, j, c, res, and sum to 0.
5+
2. We will calculate the sum of the first k elements and check if the average is greater than or equal to the threshold.
6+
3. We will increment the result if the average is greater than or equal to the threshold.
7+
4. We will iterate through the array and calculate the sum of the next k elements.
8+
5. We will check if the average is greater than or equal to the threshold and increment the result accordingly.
9+
6. We will return the result.
10+
11+
Time Complexity: O(n)
12+
Space Complexity: O(1)
13+
14+
*/
15+
public class Solution {
16+
public int NumOfSubarrays(int[] arr, int k, int threshold) {
17+
int i, j, c, res, sum; // Initialize i, j, c, res, and sum to 0.
18+
i = c = sum = res = 0; // Initialize i, c, sum, and res to 0.
19+
j = i + k - 1; // Initialize j to i + k - 1.
20+
21+
while (c <= j) { // Calculate the sum of the first k elements.
22+
sum = sum + arr[c]; // Add the element at index c to the sum.
23+
c++; // Increment c.
24+
}
25+
26+
res = (sum / k) >= threshold ? 1 : 0; // Check if the average is greater than or equal to the threshold and increment the result accordingly.
27+
28+
while (j < arr.Length) { // Iterate through the array and calculate the sum of the next k elements.
29+
sum = sum - arr[i++]; // Subtract the element at index i from the sum and increment i.
30+
j++; // Increment j.
31+
if (j < arr.Length) { // Check if j is less than the length of the array.
32+
sum = sum + arr[j]; // Add the element at index j to the sum.
33+
}
34+
else {
35+
break; // Break the loop if j is equal to or greater than the length of the array.
36+
}
37+
if ((sum / k) >= threshold) { // Check if the average is greater than or equal to the threshold.
38+
res++; // Increment the result.
39+
}
40+
}
41+
42+
return res; // Return the result.
43+
}
44+
}

0 commit comments

Comments
 (0)
Please sign in to comment.