Count Subarrays With Max Element Appearing K Times

Medium

Description

Given an integer array nums and a positive integer k, return the number of subarrays where the element with maximum value appears at least k times.

Examples

Input:nums = [1,3,2,3,3], k = 2
Output:6
Explanation:

6 subarrays with 3 appearing >= 2 times.

Input:nums = [1,4,2,1], k = 3
Output:0
Explanation:

Edge case returning zero.

Input:nums = [2,2,2,2], k = 1
Output:10
Explanation:

All elements are equal (max = 2), so every subarray contains the max element at least 1 time. Total subarrays: [2], [2,2], [2,2,2], [2,2,2,2] (4 starting at index 0) + [2], [2,2], [2,2,2] (3 starting at index 1) + [2], [2,2] (2 starting at index 2) + [2] (1 starting at index 3) = 4+3+2+1 = 10.

Constraints

  • 1 ≤ nums.length ≤ 10⁵

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!