Given an integer array nums and an integer k, return the length of the longest subarray of nums such that the frequency of every element appearing in the subarray is at most k.
A subarray is a contiguous, non-empty sequence of elements within an array.
Function Signature
def max_subarray_length(nums: list[int], k: int) -> int:
Rules
-
A subarray is
nums[i..j]
for some
i <= j
. It cannot be empty.
-
Return only the length. When several subarrays share the longest length, the answer is still that one number.
Constraints
-
1 <= len(nums) <= 10^5
-
1 <= nums[i] <= 10^9
-
1 <= k <= len(nums)
Examples
Input: nums = [1,2,3,1,2,3,1,2], k = 2
Output: 6
The subarray [1,2,3,1,2,3] contains each value exactly twice. Both subarrays of length 7 fail: the first contains 1 three times and the second contains 2 three times.
Input: nums = [1,2,1,2,1,2,1,2], k = 1
Output: 2
[1,2] has no repeated value. Any subarray of length 3 starts and ends with the same value, so that value appears twice.
Input: nums = [5,5,5,5], k = 3
Output: 3
The only subarray of length 4 is the whole array, where 5 appears four times. Any three consecutive elements are valid.