Skip to content

Commit ca489ca

Browse files
authored
Update 2537-count-the-number-of-good-subarrays.js
1 parent cf014f9 commit ca489ca

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

2537-count-the-number-of-good-subarrays.js

+39
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,42 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number}
5+
*/
6+
const countGood = function(nums, k) {
7+
let res = 0, total = 0
8+
const cnt = {}, n = nums.length
9+
10+
for(let i = 0, j = 0; i < n; i++) {
11+
12+
while(j < n && total < k) {
13+
total += diff(nums[j], 1)
14+
cnt[nums[j]] = (cnt[nums[j]] || 0) + 1
15+
j++
16+
}
17+
18+
if(total >= k) {
19+
res += n - j + 1
20+
}
21+
total += diff(nums[i], -1)
22+
cnt[nums[i]]--
23+
}
24+
25+
return res
26+
27+
function diff(num, delta) {
28+
const pre = cnt[num] || 0
29+
const old = pre * (pre - 1) / 2
30+
const post = pre + delta
31+
const cur = post * (post - 1) / 2
32+
33+
return cur - old
34+
}
35+
};
36+
37+
// another
38+
39+
140
/**
241
* @param {number[]} nums
342
* @param {number} k

0 commit comments

Comments
 (0)