Problem
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.
Examples
Example 1:
| |
Example 2:
| |
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^61 <= k <= 10^5
Solution
Method 1 - Sliding window
Here is the approach:
- Identify the Maximum Element:
- Compute the maximum value in the array since only subarrays containing this element are relevant.
- Sliding Window Logic:
- Use two pointers (
startandend) to maintain a sliding window across the array. - Within the window:
- Count how many times the maximum element appears.
- If the count of the maximum element equals
k:- Shrink the window (
start++) until the count becomes less thank. - At this point, all subarrays starting from position
starttoendare valid, and we increment our result (ans).
- Shrink the window (
- Use two pointers (
- Accumulate Results:
- Add the size of the valid range (calculated as
start) to the final result.
- Add the size of the valid range (calculated as
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n): We traverse the array once using theendpointer. Thestartpointer also progresses in a single pass over the array during adjustments. - 🧺 Space complexity:
O(1): No extra space is used beyond a few variables, as all computations are performed directly on the input array.