-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSlidingWindowMaximum.cpp
62 lines (50 loc) · 1.13 KB
/
SlidingWindowMaximum.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
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <deque>
#include <vector>
using namespace std;
// using deque
vector<int> maxSlidingWindow(vector<int> &nums, int k)
{
deque<int> dq;
vector<int> res;
// first window
for (int i = 0; i < k; i++)
{
// delete smaller value
while (dq.size() > 0 && nums[dq.back()] <= nums[i])
{
dq.pop_back();
}
// push new index values
dq.push_back(i);
}
for (int i = k; i < nums.size(); i++)
{
res.push_back(nums[dq.front()]);
// remove elements not part of current window
while (dq.size() > 0 && dq.front() <= i - k)
{
dq.pop_front();
}
// delete smaller value
while (dq.size() > 0 && nums[dq.back()] <= nums[i])
{
dq.pop_back();
}
dq.push_back(i);
}
res.push_back(nums[dq.front()]);
return res;
}
int main()
{
vector<int> nums = {1, 3, -1, -3, 5, 3, 6, 7};
int k = 3;
vector<int> ans = maxSlidingWindow(nums, k);
for (int val : ans)
{
cout << val << " ";
}
cout << endl;
return 0;
}