[LeetCode] Length of Longest Subarray With at Most K Frequency

10033. Length of Longest Subarray With at Most K Frequency

You are given an integer array nums and an integer k.

The frequency of an element x is the number of times it occurs in an array.

An array is called good if the frequency of each element in this array is less than or equal to k.

Return the length of the longest good subarray of nums.

A subarray is a contiguous non-empty sequence of elements within an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int maxSubarrayLength(vector<int>& A, int k) {
unordered_map<int, int> freq;
int res = 0, l = 0, r = 0, n = A.size();
while(r < n) {
while(r < n) {
freq[A[r]] += 1;
int cnt = freq[A[r]];
r += 1;
if(cnt > k) break;
res = max(res, r - l);
}
while(freq[A[r-1]] > k) {
--freq[A[l++]];
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/12/10/PS/LeetCode/length-of-longest-subarray-with-at-most-k-frequency/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.