JZX轻语:简

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

发表于2025年05月01日

#滑动窗口 #数组

滑动窗口的套路题目,窗口左侧每移动一位,右侧移到刚好满足条件,然后右侧后面所有的子数组都能满足条件,简单来说做法就是在每次(外层)循环中:

class Solution {
public:
    using LL = long long;
    long long countSubarrays(vector<int>& nums, int k) {
        int max_val = *std::max_element(nums.begin(), nums.end());
        LL ans {0};
        int right = 0, cnt = 0, n = nums.size();
        for (int left = 0; left < n; ++left) {
            while (right < n && cnt < k) {
                if (nums[right++] == max_val) cnt++;
            }
            if (cnt == k) ans += n - right + 1;
            if (nums[left] == max_val) cnt--;
        }
        return ans;
    }
};

相关题目:

闪念标签:LC

题目链接:https://leetcode.cn/problems/count-subarrays-where-max-element-appears-at-least-k-times/