2958. Length of Longest Subarray With at Most K Frequency Medium
1/**
2 * [2958] Length of Longest Subarray With at Most K Frequency
3 *
4 * You are given an integer array nums and an integer k.
5 * The frequency of an element x is the number of times it occurs in an array.
6 * An array is called good if the frequency of each element in this array is less than or equal to k.
7 * Return the length of the longest good subarray of nums.
8 * A subarray is a contiguous non-empty sequence of elements within an array.
9 *
10 * <strong class="example">Example 1:
11 *
12 * Input: nums = [1,2,3,1,2,3,1,2], k = 2
13 * Output: 6
14 * Explanation: The longest possible good subarray is [1,2,3,1,2,3] since the values 1, 2, and 3 occur at most twice in this subarray. Note that the subarrays [2,3,1,2,3,1] and [3,1,2,3,1,2] are also good.
15 * It can be shown that there are no good subarrays with length more than 6.
16 *
17 * <strong class="example">Example 2:
18 *
19 * Input: nums = [1,2,1,2,1,2,1,2], k = 1
20 * Output: 2
21 * Explanation: The longest possible good subarray is [1,2] since the values 1 and 2 occur at most once in this subarray. Note that the subarray [2,1] is also good.
22 * It can be shown that there are no good subarrays with length more than 2.
23 *
24 * <strong class="example">Example 3:
25 *
26 * Input: nums = [5,5,5,5,5,5,5], k = 4
27 * Output: 4
28 * Explanation: The longest possible good subarray is [5,5,5,5] since the value 5 occurs 4 times in this subarray.
29 * It can be shown that there are no good subarrays with length more than 4.
30 *
31 *
32 * Constraints:
33 *
34 * 1 <= nums.length <= 10^5
35 * 1 <= nums[i] <= 10^9
36 * 1 <= k <= nums.length
37 *
38 */
39pub struct Solution {}
40
41// problem: https://leetcode.com/problems/length-of-longest-subarray-with-at-most-k-frequency/
42// discuss: https://leetcode.com/problems/length-of-longest-subarray-with-at-most-k-frequency/discuss/?currentPage=1&orderBy=most_votes&query=
43
44// submission codes start here
45
46impl Solution {
47 pub fn max_subarray_length(nums: Vec<i32>, k: i32) -> i32 {
48 0
49 }
50}
51
52// submission codes end
53
54#[cfg(test)]
55mod tests {
56 use super::*;
57
58 #[test]
59 fn test_2958() {
60 }
61}
62
Back
© 2025 bowen.ge All Rights Reserved.