Length of Longest Subarray With at Most K Frequency - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,3,1,2,3], k = 2
›
Output:
6
💡 Note:
The whole array is good since each element appears at most 2 times: 1 appears 2 times, 2 appears 2 times, 3 appears 2 times.
Example 2 — Frequency Constraint
$
Input:
nums = [1,2,1,2,1,2,1], k = 2
›
Output:
4
💡 Note:
Longest good subarray could be [1,2,1,2] with length 4. Element 1 appears 2 times and element 2 appears 2 times.
Example 3 — Single Element
$
Input:
nums = [5,5,5,5,5], k = 4
›
Output:
4
💡 Note:
Element 5 can appear at most 4 times, so longest good subarray has length 4.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 109
- 1 ≤ k ≤ nums.length
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code