We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent cf014f9 commit ca489caCopy full SHA for ca489ca
2537-count-the-number-of-good-subarrays.js
@@ -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
40
/**
41
* @param {number[]} nums
42
* @param {number} k
0 commit comments