-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path097_Maximum of minimum for every window size.cpp
93 lines (69 loc) · 1.73 KB
/
097_Maximum of minimum for every window size.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
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
// Time Complexity -> O(N^2)
// Space Complexity -> O(N)
#include <bits/stdc++.h>
vector<int> maxMinWindow(vector<int> a, int n) {
// Write your code here.
vector<int> ans;
for(int win = 1; win <= n; ++win)
{
int i = 0, j = 0;
list<int> l;
int maxi = INT_MIN;
while(j < n)
{
while(!l.empty() and l.back() > a[j])
l.pop_back();
l.push_back(a[j]);
if(j - i + 1 == win)
{
maxi = max(maxi, l.front());
if (a[i] == l.front()) {
l.pop_front();
}
++i;
}
++j;
}
ans.push_back(maxi);
}
return ans;
}
// Time Complexity -> O(N)
// Space Complexity -> O(3N)
#include <bits/stdc++.h>
vector<int> maxMinWindow(vector<int> a, int n) {
// Write your code here.
vector<int> left(n, 0), right(n,0), ans(n,INT_MIN);
stack<int> st;
for(int i = 0; i < n; ++i)
{
while(!st.empty() and a[st.top()] >= a[i])
st.pop();
if(st.empty())
left[i] = 0;
else
left[i] = st.top() + 1;
st.push(i);
}
while(!st.empty())
st.pop();
for(int i = n-1; i >= 0; --i)
{
while(!st.empty() and a[st.top()] >= a[i])
st.pop();
if(st.empty())
right[i] = n-1;
else
right[i] = st.top() - 1;
st.push(i);
}
for(int i = 0; i < n; ++i)
{
ans[right[i] - left[i]] = max(ans[right[i] - left[i]], a[i]);
}
for(int i = n-2; i >= 0; --i)
{
ans[i] = max(ans[i], ans[i+1]);
}
return ans;
};