-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
35 lines (30 loc) · 857 Bytes
/
Copy pathsolution.cpp
File metadata and controls
35 lines (30 loc) · 857 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
class Solution
{
public:
vector<int> maxOfSubarrays(vector<int> &arr, int k)
{
deque<int> dq; // stores indexes
vector<int> result;
for (int i = 0; i < arr.size(); i++)
{
// Remove elements that are out of this window
if (!dq.empty() && dq.front() == i - k)
{
dq.pop_front();
}
// Remove smaller elements from the back
while (!dq.empty() && arr[dq.back()] <= arr[i])
{
dq.pop_back();
}
// Add current index
dq.push_back(i);
// Window becomes valid when i >= k - 1
if (i >= k - 1)
{
result.push_back(arr[dq.front()]);
}
}
return result;
}
};