forked from chiriacandrei25/The-Bible-of-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSliding Window Technique.cpp
49 lines (45 loc) · 1.04 KB
/
Sliding Window Technique.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 <iostream>
using namespace std;
const int Nmax = 100005;
int fr[Nmax];
int slidingWindow(int *a, int n, int k) {
int cnt = 0, ans = 0, Right;
for(Right = 1; Right <= n; Right++) {
if(++fr[a[Right]] == 1)
cnt++;
if(cnt > k)
break;
}
if(cnt <= k)
return n;
if(--fr[a[Right]] == 0)
cnt--;
Right--; ans = Right;
for(int Left = 2; Left <= n; Left++) {
if(--fr[a[Left - 1]] == 0)
cnt--;
while(Right < n) {
Right++;
if(++fr[a[Right]] == 1)
cnt++;
if(cnt > k)
break;
}
if(cnt <=
k)
return max(ans, n - Left + 1);
if(--fr[a[Right]] == 0)
cnt--;
Right--;
ans = max(ans, Right - Left + 1);
}
}
int main()
{
int a[Nmax], n, k;
cin >> n >> k;
for(int i = 1; i <= n; i++)
cin >> a[i];
cout << slidingWindow(a, n, k);
return 0;
}