-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathSlidingWindowMax.cpp
More file actions
67 lines (55 loc) · 1.59 KB
/
SlidingWindowMax.cpp
File metadata and controls
67 lines (55 loc) · 1.59 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
#include <deque>
#include <vector>
using namespace std;
vector<int> SlidingWindow(int arr[], int k, int size)
{
vector<int> answer;
deque<int> windowQ;
//initializing a deque
for (int i = 0; i < k; i++)//for the first k elements, push them into the deque while taking care fo the fact that their
//are no unnecessary element. pop from back the elements that are less than the current element to be inserted
{
while (!windowQ.empty() && arr[i] >= arr[windowQ.back()])
{
windowQ.pop_back();
}
windowQ.push_back(i);
}
answer.push_back(arr[windowQ.front()]);
//max element of this window is at front
for (int i = k; i < size; i++)
//repeating the above task for the rest of the array while keeping in mind the changing windows, and hence
//popping the not required elements form the front that are not part of the new window
{
while (!windowQ.empty() && windowQ.front() <= i - k)
{
windowQ.pop_front();
}
while (!windowQ.empty() && arr[i] >= arr[windowQ.back()])
{
windowQ.pop_back();
}
windowQ.push_back(i);
answer.push_back(arr[windowQ.front()]);
}
return answer;
}
int main()
{
int size;
cout<<"Size: ";
cin >> size;
int *array = new int[size];
cout<<"Array: ";
for (int i = 0; i < size; i++)
{
scanf("%d", &array[i]);
}
int k;
cout<<"k: ";
cin>>k;
vector<int> a=SlidingWindow(array,k,size);
for(int i:a)
cout<<i<<" ";
}