Skip to content

Files

Latest commit

8dde2dd · Aug 1, 2024

History

History

length-of-longest-subarray-with-at-most-k-frequency

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Aug 1, 2024
Dec 9, 2023
Dec 9, 2023
Dec 9, 2023

Length of longest subarray with at most k frequency

Problem link

Solutions

Solution.py

# https://leetcode.com/problems/length-of-longest-subarray-with-at-most-k-frequency/

class Solution:
    def maxSubarrayLength(self, nums: List[int], k: int) -> int:
        n, l, best = len(nums), 0, 0
        cnt = defaultdict(int)
        for r in range(n):
            cnt[nums[r]] += 1
            while cnt[nums[r]] > k:
                cnt[nums[l]] -= 1
                l += 1
            best = max(best, r - l + 1)
        return best

Tags