|
| 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 | +} |