[LeetCode] 2962. Count Subarrays Where Max Element Appears at Least K Times

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 <= 105
1 <= nums[i] <= 106
1 <= k <= 105

统计最大元素出现至少 K 次的子数组。

给你一个整数数组 nums 和一个 正整数 k 。

请你统计有多少满足 「 nums 中的 最大 元素」至少出现 k 次的子数组,并返回满足这一条件的子数组的数目。

子数组是数组中的一个连续元素序列。

思路

不难想到是滑动窗口。但是注意这道题问的是最大元素出现至少 k 次的子数组,而不是恰好 k 次。如果问的是恰好 k 次的话,当右指针遇到第 k 个最大元素的时候,左指针就可以开始动了,类似76题那种形式。但是这道题当右指针移动到第 k 个最大元素的时候,因为左右指针中间包含了 k 个最大元素,所以左指针及其左边,都是合法的子数组,都包含了起码 k 个最大元素。

复杂度

时间O(n)
空间O(n)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public long countSubarrays(int[] nums, int k) {
int max = Arrays.stream(nums).max().orElseThrow();
int start = 0;
int end = 0;
int count = 0;
long res = 0;
while (end < nums.length) {
int cur = nums[end++];
if (cur == max) {
count++;
}
while (count >= k) {
if (nums[start++] == max) {
count--;
}
}
res += start;
}
return res;
}
}

[LeetCode] 2962. Count Subarrays Where Max Element Appears at Least K Times
https://shurui91.github.io/posts/1261282593.html
Author
Aaron Liu
Posted on
March 29, 2024
Licensed under