forked from Nimesh-Srivastava/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0992.cpp
More file actions
43 lines (37 loc) · 890 Bytes
/
0992.cpp
File metadata and controls
43 lines (37 loc) · 890 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution
{
public:
int ans(vector<int> &num, int t)
{
if (t == 0)
return 0;
int n = num.size(), total = 0, diff = 0, j = 0;
vector<int> cnt(20002);
for (int i = 0; i < n; i++)
{
if (cnt[num[i]] == 0)
diff++;
cnt[num[i]]++;
if (diff <= t)
{
total += (i - j + 1);
}
else
{
while (j < n && j <= i && diff > t)
{
cnt[num[j]]--;
if (cnt[num[j]] == 0)
diff--;
j++;
}
total += (i - j + 1);
}
}
return total;
}
int subarraysWithKDistinct(vector<int> &nums, int k)
{
return ans(nums, k) - ans(nums, k - 1);
}
};