-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSliding_Window_Maximum.cpp
More file actions
97 lines (88 loc) · 1.77 KB
/
Copy pathSliding_Window_Maximum.cpp
File metadata and controls
97 lines (88 loc) · 1.77 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
*/
#include <iostream>
#include <vector>
#include <deque>
using namespace std;
vector<int> maxSlidingWindow(vector<int>& nums, int k)
{
vector<int> result;
deque<int> dq;
if (nums.empty())
{
return result;
}
/* Finding maximum of the first sliding window - start */
for (int i = 0; i < k; i++)
{
if(i == 0)
{
// First element of the array
dq.push_back(i);
}
else
{
while (nums[i] > nums[dq.back()])
{
dq.pop_back();
if (dq.empty())
{
break;
}
}
dq.push_back(i);
}
}
// maximum of the first sliding window
result.push_back(nums[dq.front()]);
/* Finding maximum of the first sliding window - end */
/* Finding maximum of the rest sliding windows - start */
for (int i = k; i < nums.size(); i++)
{
if (dq.front() <= i - k)
{
dq.pop_front();
}
if(dq.empty())
{
dq.push_back(i);
}
else
{
while (nums[i] > nums[dq.back()])
{
dq.pop_back();
if (dq.empty())
{
break;
}
}
dq.push_back(i);
}
result.push_back(nums[dq.front()]);
}
/* Finding maximum of the rest sliding windows - end */
return result;
}
int main()
{
vector<int> arr_in = { 9, 10, 9, -7, -4, -8, 2, -6 };
vector<int> arr_out = maxSlidingWindow(arr_in, 5);
for (int i = 0; i < arr_out.size(); i++)
{
cout << arr_out[i] << " ";
}
cout << endl;
return 0;
}