Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit169a4e9

Browse files
authored
Merge pull requestneetcode-gh#3690 from vermavarun/main
Create 1343-number-of-sub-arraysofSize-k-and-average-greaterthanor-equal-to-threshold.cs
2 parents3060b48 +0cdc715 commit169a4e9

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
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+
publicclassSolution{
16+
publicintNumOfSubarrays(int[]arr,intk,intthreshold){
17+
inti,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+
returnres;// Return the result.
43+
}
44+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp