Dashboard Temp Share Shortlinks Frames API

HTMLify

subarrays-with-at-most-k-distinct-integers.py
Views: 7 | Author: prakhardoneria
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
    def countAtMostK(self, arr, k):
        if k == 0:
            return 0
        
        n = len(arr)
        left = 0
        right = 0
        count = 0
        freq = {}
        
        while right < n:
            freq[arr[right]] = freq.get(arr[right], 0) + 1
            
            while len(freq) > k:
                freq[arr[left]] -= 1
                if freq[arr[left]] == 0:
                    del freq[arr[left]]
                left += 1
            
            count += (right - left + 1)
            right += 1
            
        return count