Count Subarrays Where Max Element Appears at Least K Times Problem
#2962
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2962.
You are given an integer array nums and a positive integer k.
Return the number of subarrays where the maximum element of nums appears at least k times in that subarray.
A subarray is a contiguous sequence of elements within an array.
Example 1:
Input: nums = [1,3,2,3,3], k = 2
Output: 6
Explanation: The subarrays that contain the element 3 at least 2 times are: [1,3,2,3], [1,3,2,3,3], [3,2,3], [3,2,3,3], [2,3,3] and [3,3].
Example 2:
Input: nums = [1,4,2,1], k = 3
Output: 0
Explanation: No subarray contains the element 4 at least 3 times.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^61 <= k <= 10^5
Solution
Approach: Two Pointers
Let mx be the maximum of the array. For a fixed left end i, advance j until the window [i, j) holds k copies of mx. Then every right end from j - 1 to the end of the array works, which adds n - j + 1 subarrays. Move i forward, remove nums[i] from the count if it equals mx, and repeat; j never moves backwards. Stop when the window can no longer reach k copies.
Complexity: O(n) time and O(1) extra space.
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
mx = max(nums)
n = len(nums)
ans = cnt = j = 0
for x in nums:
while j < n and cnt < k:
cnt += nums[j] == mx
j += 1
if cnt < k:
break
ans += n - j + 1
cnt -= x == mx
return ans