LeetCode 2962.统计最大元素出现至少K次的子数组
题目:
给你一个整数数组 nums
和一个 正整数 k
。
请你统计有多少满足 「 nums
中的 最大 元素」至少出现 k
次的子数组,并返回满足这一条件的子数组的数目。子数组是数组中的一个连续元素序列。
思路:
代码:
class Solution {public long countSubarrays(int[] nums, int k) {int n = nums.length;int left = 0;long ans = 0;int count = 0;int maxV = Integer.MIN_VALUE;for (int num : nums) {maxV = Math.max(maxV, num);}for (int right = 0; right < n; right++) {if (nums[right] == maxV) {count++;}while (count >= k) {if (nums[left] == maxV) {count--;}left++;}ans += left; }return ans;}
}
性能: