Show problems as
Classic problem #2962MediumArraySliding Window

Count Subarrays Where Max Element Appears at Least K Times

Real-world version: Stretches Holding the Top Reading k Times
Tracked 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)