Skip to content

2958. Length of Longest Subarray With at Most K Frequency 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int maxSubarrayLength(vector<int>& nums, int k) {
    int ans = 0;
    unordered_map<int, int> count;

    for (int l = 0, r = 0; r < nums.size(); ++r) {
      ++count[nums[r]];
      while (count[nums[r]] == k + 1)
        --count[nums[l++]];
      ans = max(ans, r - l + 1);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int maxSubarrayLength(int[] nums, int k) {
    int ans = 0;
    Map<Integer, Integer> count = new HashMap<>();

    for (int l = 0, r = 0; r < nums.length; ++r) {
      count.merge(nums[r], 1, Integer::sum);
      while (count.get(nums[r]) == k + 1)
        count.merge(nums[l++], -1, Integer::sum);
      ans = Math.max(ans, r - l + 1);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def maxSubarrayLength(self, nums: list[int], k: int) -> int:
    ans = 0
    count = collections.Counter()

    l = 0
    for r, num in enumerate(nums):
      count[num] += 1
      while count[num] == k + 1:
        count[nums[l]] -= 1
        l += 1
      ans = max(ans, r - l + 1)

    return ans