Skip to content

Commit b6ddeee

Browse files
committedApr 16, 2025
Add solution #2537
1 parent e2ca5ae commit b6ddeee

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed
 

‎README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,320 LeetCode solutions in JavaScript
1+
# 1,321 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1243,6 +1243,7 @@
12431243
2523|[Closest Prime Numbers in Range](./solutions/2523-closest-prime-numbers-in-range.js)|Medium|
12441244
2529|[Maximum Count of Positive Integer and Negative Integer](./solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
12451245
2535|[Difference Between Element Sum and Digit Sum of an Array](./solutions/2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy|
1246+
2537|[Count the Number of Good Subarrays](./solutions/2537-count-the-number-of-good-subarrays.js)|Medium|
12461247
2542|[Maximum Subsequence Score](./solutions/2542-maximum-subsequence-score.js)|Medium|
12471248
2551|[Put Marbles in Bags](./solutions/2551-put-marbles-in-bags.js)|Hard|
12481249
2559|[Count Vowel Strings in Ranges](./solutions/2559-count-vowel-strings-in-ranges.js)|Medium|
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 2537. Count the Number of Good Subarrays
3+
* https://leetcode.com/problems/count-the-number-of-good-subarrays/
4+
* Difficulty: Medium
5+
*
6+
* Given an integer array nums and an integer k, return the number of good subarrays of nums.
7+
*
8+
* A subarray arr is good if there are at least k pairs of indices (i, j) such that i < j
9+
* and arr[i] == arr[j].
10+
*
11+
* A subarray is a contiguous non-empty sequence of elements within an array.
12+
*/
13+
14+
/**
15+
* @param {number[]} nums
16+
* @param {number} k
17+
* @return {number}
18+
*/
19+
var countGood = function(nums, k) {
20+
const frequency = new Map();
21+
let result = 0;
22+
let currentPairs = 0;
23+
let left = 0;
24+
25+
for (let right = 0; right < nums.length; right++) {
26+
const num = nums[right];
27+
const prevCount = frequency.get(num) || 0;
28+
currentPairs += prevCount;
29+
frequency.set(num, prevCount + 1);
30+
31+
while (currentPairs >= k) {
32+
result += nums.length - right;
33+
const leftNum = nums[left];
34+
const leftCount = frequency.get(leftNum);
35+
currentPairs -= leftCount - 1;
36+
frequency.set(leftNum, leftCount - 1);
37+
left++;
38+
}
39+
}
40+
41+
return result;
42+
};

0 commit comments

Comments
 (0)
Please sign in to comment.