Skip to content

Commit 734f964

Browse files
authored
Create 992-subarrays-with-k-different-integers.js
1 parent 9dc021f commit 734f964

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @param {number[]} A
3+
* @param {number} K
4+
* @return {number}
5+
*/
6+
const subarraysWithKDistinct = function(A, K) {
7+
let res = 0,
8+
prefix = 0
9+
const m = new Array(A.length + 1).fill(0)
10+
for (let i = 0, j = 0, cnt = 0; i < A.length; ++i) {
11+
if (m[A[i]]++ === 0) ++cnt
12+
if (cnt > K) {
13+
--m[A[j++]]
14+
--cnt
15+
prefix = 0
16+
}
17+
while (m[A[j]] > 1) {
18+
++prefix
19+
--m[A[j++]]
20+
}
21+
if (cnt === K) res += prefix + 1
22+
}
23+
return res
24+
}

0 commit comments

Comments
 (0)