Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold Problem
Description
LeetCode Problem 1343.
Given an array of integers arr and two integers k and threshold, return the number of sub-arrays of size k and average greater than or equal to threshold.
Example 1:
Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4
Output: 3
Explanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold).
Example 2:
Input: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5
Output: 6
Explanation: The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.
Constraints:
1 <= arr.length <= 10^51 <= arr[i] <= 10^41 <= k <= arr.length0 <= threshold <= 10^4
Solution
Approach: Sliding Window
An average of k numbers is at least threshold exactly when their sum is at least k * threshold. Comparing sums avoids division and the rounding problems that come with it (averages need not be integers, as Example 2 points out).
Compute the sum of the first k numbers. Then slide the window one step at a time: add the number that enters on the right and subtract the one that leaves on the left, s += arr[i] - arr[i - k]. Count every window whose sum reaches k * threshold.
The largest window sum is 10^5 * 10^4 = 10^9, and k * threshold is at most the same, so 32-bit integers are enough.
Complexity: O(n) time and O(1) extra space.
class Solution:
def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:
target = k * threshold # average >= threshold <=> sum >= k * threshold
s = sum(arr[:k])
ans = int(s >= target)
for i in range(k, len(arr)):
s += arr[i] - arr[i - k] # slide the window one step right
ans += s >= target
return ans