Problem 311878 · easy · Level 03 Linear Management & Searching

Windows Over the Threshold

sliding window · fixed-size window · counting

A sensor produces integer readings. An alarm fires for every block of exactly k consecutive readings whose average is greater than or equal to threshold. Return how many such blocks exist. If k is larger than the number of readings, return 0.

Examples

Input:  readings = [3, 1, 4, 6, 2, 5, 7], k = 3, threshold = 4
Output: 3
Explanation: the blocks [4,6,2], [6,2,5] and [2,5,7] have sums 12, 13 and 14,
so their averages are 4 or more; [3,1,4] and [1,4,6] average less than 4.

Input:  readings = [6, 1, 8, 2, 9, 0, 7], k = 2, threshold = 5
Output: 2
Explanation: [8,2] averages exactly 5 and [2,9] averages 5.5.

Constraints

  • 0 <= len(readings) <= 10**5
  • 1 <= k <= 10**5, 0 <= readings[i], threshold <= 10**4
  • Target complexity: O(n) time; an O(n·k) re-sum per window is too slow for the largest tests.

Goals

  • Slide a fixed window while keeping its sum up to date
  • Compare an average with a threshold using integer arithmetic
Starting Python…