Skip to content

Latest commit

 

History

History

2962

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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

Solution 1. Map of first occurrence

// OJ: https://leetcode.com/problems/count-subarrays-where-max-element-appears-at-least-k-times
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
    long long countSubarrays(vector<int>& A, int k) {
        long long N = A.size(), ans = 0, cnt = 0, mx = *max_element(begin(A), end(A));
        unordered_map<int, int> m; // mapping from A[i] to the index of its first occurrence
        for (int i = 0; i < N; ++i) {
            cnt += A[i] == mx;
            if (cnt && m.count(cnt) == 0) m[cnt] = i; // Store the index of its first occurrence
            if (m.count(cnt - k + 1)) {
                ans += m[cnt - k + 1] + 1; // add 1 + frequency of the first occurrence of cnt-k+1
            }
        }
        return ans;
    }
};

Solution 2. Find Minimum Sliding Window

// OJ: https://leetcode.com/problems/count-subarrays-where-max-element-appears-at-least-k-times
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
    long long countSubarrays(vector<int>& A, int k) {
        long long N = A.size(), ans = 0, cnt = 0, mx = *max_element(begin(A), end(A)), i = 0, j = 0;
        for (; j < N; ++j) {
            cnt += A[j] == mx;
            while (cnt >= k) cnt -= A[i++] == mx;
            ans += i;
        }
        return ans;
    }
};

Discuss

https://leetcode.com/problems/count-subarrays-where-max-element-appears-at-least-k-times/solutions/4384450/map-of-first-occurrence-o-n-time/