serega1112

992

Dec 15th, 2020
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.71 KB | None | 0 0
  1. class Solution:
  2.     def subarraysWithKDistinct(self, A: List[int], K: int) -> int:
  3.        
  4.         def at_most_k_distinct(nums, k):
  5.             l = r = res = 0
  6.             memo = defaultdict(int)
  7.            
  8.             while r < len(nums):
  9.                 memo[nums[r]] += 1
  10.                 if memo[nums[r]] == 1:
  11.                     k -= 1
  12.                 r += 1
  13.                 while k < 0:
  14.                     memo[nums[l]] -= 1
  15.                     if memo[nums[l]] == 0:
  16.                         k += 1
  17.                     l += 1
  18.                
  19.                 res += r - l
  20.                
  21.             return res
  22.        
  23.         return at_most_k_distinct(A, K) - at_most_k_distinct(A, K - 1)
Advertisement
Add Comment
Please, Sign In to add comment