-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path992.py
More file actions
33 lines (26 loc) · 909 Bytes
/
992.py
File metadata and controls
33 lines (26 loc) · 909 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# leetcode problem no. 992(Hard )
class Solution:
def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:
distinctCount = defaultdict(int)
totalCount = 0
left = 0
right = 0
currCount = 0
while right < len(nums):
distinctCount[nums[right]] += 1
if distinctCount[nums[right]] == 1:
k -= 1
if k < 0:
distinctCount[nums[left]] -= 1
if distinctCount[nums[left]] == 0:
k += 1
left += 1
currCount = 0
if k == 0:
while distinctCount[nums[left]] > 1:
distinctCount[nums[left]] -= 1
left += 1
currCount += 1
totalCount += (currCount + 1)
right += 1
return totalCount