[InterviewBit] Sliding Window Maximum

Sliding Window Maximum

  • monotonic stack solution
  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
vector<int> Solution::slidingMaximum(const vector<int> &A, int B) {
deque<int> st;
vector<int> res;
for(int i = 0; i < A.size(); i++) {
while(!st.empty() and A[st.back()] <= A[i]) st.pop_back();
st.push_back(i);
while(!st.empty() and st.front() <= i - B) st.pop_front();
if(i >= B - 1) res.push_back(A[st.front()]);
}
return res;
}
  • heap solution
  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
vector<int> Solution::slidingMaximum(const vector<int> &A, int B) {
priority_queue<int> window, cut;
vector<int> res;
for(int i = 0; i < A.size(); i++) {
if(i >= B) cut.push(A[i-B]);
window.push(A[i]);
while(!cut.empty() and cut.top() == window.top()) {
cut.pop();
window.pop();
}
if(i >= B - 1) res.push_back(window.top());
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/15/PS/interviewbit/sliding-window-maximum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.