Problem Description
Given an integer array and two integers k and threshold, return the number of sub-arrays of size k whose average is greater than or equal to threshold.
Key Insights
- Use the sliding window technique to efficiently compute the sum of each subarray of size k.
- Compare the sum directly against k * threshold to determine if the average meets the requirement.
- Avoid recalculating the sum from scratch for each window by removing the element that is exiting and adding the new element coming in.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the array. Space Complexity: O(1), constant additional space is used.
Solution
We apply a sliding window approach:
- Calculate the sum of the first k elements.
- Check if this sum is greater than or equal to k * threshold.
- Slide the window across the array by subtracting the first element of the current window and adding the next element.
- Increment a counter each time the sum of the window satisfies the condition.
- Return the count of valid subarrays.