-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathSliding_window_maximum.cpp
More file actions
53 lines (44 loc) · 865 Bytes
/
Sliding_window_maximum.cpp
File metadata and controls
53 lines (44 loc) · 865 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
44
45
46
47
48
49
50
51
52
53
#include <bits/stdc++.h>
using namespace std;
// function
void maxSlidingWindow(vector<int> &nums, int k)
{
vector<int> ans;
int i = 0, j = 0;
int n = nums.size();
int mx, pm;
deque<int> q;
while (j < n)
{
while (!q.empty() && q.back() < nums[j])
{
q.pop_back();
}
q.push_back(nums[j]);
if (j - i + 1 < k)
{
j++;
}
else if (j - i + 1 == k)
{
ans.push_back(q.front());
if (nums[i] == q.front())
{
q.pop_front();
}
i++;
j++;
}
}
for (int i = 0; i < ans.size(); i++)
{
cout << ans[i] << " ";
}
}
// driver code
int main()
{
vector<int> v = {1, 3, -1, -3, 5, 3, 6, 7};
maxSlidingWindow(v, 3);
return 0;
}