Classic problem #2962MediumArraySliding Window
Count Subarrays Where Max Element Appears at Least K Times
Real-world version: Stretches Holding the Top Reading k TimesTracked in this browser only
Read Count Subarrays Where Max Element Appears at Least K Times on LeetCode(opens in a new tab)
The statement here is our own: the same inputs, outputs and technique.
A log holds the readings readings. Let the top reading be the largest reading anywhere in the log.
Return how many stretches of neighbouring readings hold the top reading at least k times.
Examples
Example 1
- Input
- readings = [2, 2, 2], k = 2
- Output
- 3
The top reading is two and every reading is one. The stretches holding it at least twice are the two neighbouring pairs and the whole log.
Example 2
- Input
- readings = [5], k = 1
- Output
- 1
One reading is itself the top reading, and the single stretch holds it once.
Example 3
- Input
- readings = [1, 2, 1], k = 2
- Output
- 0
The top reading is two and the log holds only one of it, so no stretch can hold it twice.
Constraints
- 1 <= readings.length <= 10^5
- 1 <= readings[i] <= 10^6
- 1 <= k <= 10^5
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
Python
def count_subarrays(readings: list[int], k: int) -> int:Java
public long countSubarrays(int[] readings, int k)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's