Skip to content

Commit e350f15

Browse files
authored
Create 2537.Count-the-Number-of-Good-Subarrays.cpp
1 parent a839cf3 commit e350f15

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
using LL = long long;
2+
class Solution {
3+
LL total = 0;
4+
LL ret = 0;
5+
public:
6+
long long countGood(vector<int>& nums, int k)
7+
{
8+
int n = nums.size();
9+
int j = 0;
10+
unordered_map<int,int>count;
11+
12+
for (int i=0; i<n; i++)
13+
{
14+
while (j<n && total < k)
15+
{
16+
total += diff(count, nums[j], 1);
17+
count[nums[j]]++;
18+
j++;
19+
}
20+
if (total >= k)
21+
ret += n-j+1;
22+
23+
total += diff(count, nums[i], -1);
24+
count[nums[i]]--;
25+
}
26+
27+
return ret;
28+
}
29+
30+
LL diff(unordered_map<int,int>&count, int num, int d)
31+
{
32+
LL m = count[num];
33+
LL old = m*(m-1)/2;
34+
m += d;
35+
LL now = m*(m-1)/2;
36+
return now - old;
37+
}
38+
};

0 commit comments

Comments
 (0)