Count how many contiguous subarrays of length k have an average at least threshold.
Grumpy Bookstore Owner-style fixed window average check
gfgProblem
Given an integer array arr, an integer k, and an integer threshold, count the number of contiguous subarrays of length exactly k whose average value is greater than or equal to threshold.
A subarray is a contiguous segment of the array.
Because averages may be fractional, compare using the sum of the subarray rather than computing the average directly.
Goal
Return the number of length-k subarrays where:
Equivalently, count windows whose sum is at least k * threshold.
Input Format
arr: integer arrayk: positive integerthreshold: integer
The input is provided as these three values.
Output Format
Return an integer: the number of contiguous subarrays of length k whose average is at least threshold.
Constraints
1 <= k <= arr.length- Elements of
arrandthresholdare integers - Use a linear-time approach for best performance
- The answer fits in a 32-bit signed integer
Example 1
Input
arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4
Output
3
Explanation
The length-3 subarrays with average at least 4 are [2,5,5], [5,5,5], and [5,5,8]. Their sums are 12, 15, and 18, each at least 3 * 4 = 12.
Example 2
Input
arr = [1,1,1,1,1], k = 1, threshold = 1
Output
5
Explanation
Every single element forms a length-1 subarray with average 1, which is at least the threshold.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.