-
Notifications
You must be signed in to change notification settings - Fork 0
/
subarray-distinct-values.cpp
49 lines (48 loc) · 1.04 KB
/
subarray-distinct-values.cpp
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
44
45
46
47
48
49
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n, k;
cin >> n >> k;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
long long ans = (n + n - k + 1) * k / 2;
map<int, int> memo;
for (int i = 0; i < k; i++) {
memo[a[i]]++;
}
// Iterate over all subarrays with lengths k + 1 ... n
for (int len = k + 1; len <= n; len++) {
bool stop = true;
map<int, int> cnt = memo;
cnt[a[len - 1]]++;
if (cnt.size() <= k) {
ans++;
}
int i = 0, j = len - 1;
while (j + 1 < n) {
// remove first element
cnt[a[i]]--;
if (cnt[a[i]] == 0) {
cnt.erase(a[i]);
}
i++;
// add next element
j++;
cnt[a[j]]++;
if (cnt.size() <= k) {
ans++;
stop = false;
}
}
memo[a[len - 1]]++;
// If a subarray with length len didn't have <= k distinct values,
// there is no point at looking at a subarray with length len + 1.
if (stop) {
break;
}
}
cout << ans << "\n";
return 0;
}