Input: nums =[1,2,3,1,2,3,1,2], k =2 Output:6 Explanation: The longest possible good subarray is[1,2,3,1,2,3] since the values 1,2, and 3 occur at most twice inthis subarray. Note that the subarrays [2,3,1,2,3,1] and [3,1,2,3,1,2] are also good. It can be shown that there are no good subarrays with length more than 6.
Input: nums =[1,2,1,2,1,2,1,2], k =1 Output:2 Explanation: The longest possible good subarray is[1,2] since the values 1 and 2 occur at most once inthis subarray. Note that the subarray [2,1]is also good. It can be shown that there are no good subarrays with length more than 2.
Input: nums =[5,5,5,5,5,5,5], k =4 Output:4 Explanation: The longest possible good subarray is[5,5,5,5] since the value 5 occurs 4 times inthis subarray. It can be shown that there are no good subarrays with length more than 4.
To find the longest subarray where no element appears more than k times, we can use a sliding window. We expand the window to the right, and if any element’s frequency exceeds k, we shrink the window from the left until all frequencies are at most k.
classSolution {
public:int maxSubarrayLength(vector<int>& nums, int k) {
unordered_map<int, int> freq;
int l =0, ans =0;
for (int r =0; r < nums.size(); ++r) {
freq[nums[r]]++;
while (freq[nums[r]] > k) {
freq[nums[l]]--;
l++;
}
ans = max(ans, r - l +1);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
funcmaxSubarrayLength(nums []int, kint) int {
freq:=map[int]int{}
l, ans:=0, 0forr, x:=rangenums {
freq[x]++forfreq[x] > k {
freq[nums[l]]--l++ }
ifr-l+1 > ans { ans = r-l+1 }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
publicintmaxSubarrayLength(int[] nums, int k) {
Map<Integer, Integer> freq =new HashMap<>();
int l = 0, ans = 0;
for (int r = 0; r < nums.length; r++) {
freq.put(nums[r], freq.getOrDefault(nums[r], 0) + 1);
while (freq.get(nums[r]) > k) {
freq.put(nums[l], freq.get(nums[l]) - 1);
l++;
}
ans = Math.max(ans, r - l + 1);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funmaxSubarrayLength(nums: IntArray, k: Int): Int {
val freq = mutableMapOf<Int, Int>()
var l = 0var ans = 0for (r in nums.indices) {
freq[nums[r]] = freq.getOrDefault(nums[r], 0) + 1while (freq[nums[r]]!! > k) {
freq[nums[l]] = freq[nums[l]]!! - 1 l++ }
ans = maxOf(ans, r - l + 1)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defmaxSubarrayLength(self, nums: list[int], k: int) -> int:
from collections import defaultdict
freq = defaultdict(int)
l = ans =0for r, x in enumerate(nums):
freq[x] +=1while freq[x] > k:
freq[nums[l]] -=1 l +=1 ans = max(ans, r - l +1)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnmax_subarray_length(nums: Vec<i32>, k: i32) -> i32 {
use std::collections::HashMap;
letmut freq = HashMap::new();
let (mut l, mut ans) = (0, 0);
for (r, &x) in nums.iter().enumerate() {
*freq.entry(x).or_insert(0) +=1;
while freq[&x] > k {
*freq.get_mut(&nums[l]).unwrap() -=1;
l +=1;
}
ans = ans.max(r asi32- l asi32+1);
}
ans
}
}