LeetCode Daily Practice Problem : 2962. Count Subarrays Where Max Element Appears at Least K Times
Problem Statement
Number of Subarrays with Bounded Maximum
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⁵
- 1 <= nums[i] <= 10⁶
- 1 <= k <= 10⁵
Intuition
To solve this problem, we can use the sliding window technique. We initialize and find the maximum element in the given array. Then, for each right index r
, we find the subarray with k
maximum elements. All subarrays bigger than it satisfy the condition. Hence, we will manipulate the left pointer to achieve this.
Approach
- Initialize the maximum element in the array and two pointers
l
andr
. - Iterate through the array with the right pointer
r
. - If the element at
r
is the maximum element, incrementmax_cnt
. - While
max_cnt
is greater thank
or the element at the left pointerl
is not the maximum element, move the left pointerl
forward and decrementmax_cnt
. - If
max_cnt
becomes equal tok
, increment the count of subarrays byl + 1
. - Return the count.
Time Complexity
The time complexity of this approach is O(n), where n is the size of the given array nums
.
Space Complexity
The space complexity of this approach is O(1), as we are using only a constant amount of extra space.
Code
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
max_ele=max(nums)
max_cnt=0
cnt=0
l=0
for r in range(len(nums)):
if nums[r]==max_ele:
max_cnt+=1
while max_cnt>k or nums[l]!=max_ele:
if nums[l]==max_ele:
max_cnt-=1
l+=1
if max_cnt==k:
cnt+=(l+1)
return cnt