Length of Longest Subarray With at Most K Frequency

Medium Topics Company Tags

Return the length of the longest contiguous subarray of nums in which every distinct value occurs at most k times. The limit applies separately to each value.

Example 1:

Input: nums = [1,2,1,2,3]
k = 1

Output: 3

Explanation: The final three values [1,2,3] are all distinct and form a valid subarray of length 3. Every longer subarray repeats a value, which exceeds k = 1.

Example 2:

Input: nums = [4,4,4]
k = 2

Output: 2

Explanation: Any two adjacent values form a valid subarray. All three together would contain three copies of 4, so the maximum length is 2.

Example 3:

Input: nums = [2,3,2]
k = 3

Output: 3

Explanation: No value in the full array occurs more than three times, so all three elements can be kept.

Constraints:

  • 1 <= nums.length <= 100000
  • 1 <= nums[i] <= 1000000000
  • 1 <= k <= nums.length


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.