forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path239-Sliding-Window-Maximum.cpp
More file actions
39 lines (31 loc) · 890 Bytes
/
239-Sliding-Window-Maximum.cpp
File metadata and controls
39 lines (31 loc) · 890 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
/*
Given int array & sliding window size k, return max sliding window
Ex. nums = [1,3,-1,-3,5,3,6,7] k = 3 -> [3,3,5,5,6,7]
Sliding window deque, ensure monotonic decr, leftmost largest
Time: O(n)
Space: O(n)
*/
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
deque<int> dq;
vector<int> result;
int i = 0;
int j = 0;
while (j < nums.size()) {
while (!dq.empty() && nums[dq.back()] < nums[j]) {
dq.pop_back();
}
dq.push_back(j);
if (i > dq.front()) {
dq.pop_front();
}
if (j + 1 >= k) {
result.push_back(nums[dq.front()]);
i++;
}
j++;
}
return result;
}
};