# Sliding window (data structure)

Posted by cuteflower on Mon, 13 Apr 2020 16:19:51 +0200

Sliding window: there are two pointers L,R. Add a number r to move to the right, and subtract a number L to move to the right.

Generally, it is necessary to maintain the maximum or minimum value in the window, and the query complexity can be O (1).

Generally, two-way queue assistance is needed, such as Title: sliding window

Suppose it is a window that needs to maintain the maximum value, then the array in the two-way queue should be "large - > small",

In order to meet this condition, when the number x is added later, the number less than or equal to x needs to be ejected and then pushed into the bidirectional queue,

Why do I need to pop up the equal? Because the subscript of x must be larger than that of the pop-up number, so the expiration time of x is later than that of the previous one. That's not so good

Pop up the same number of early expirations.

When maintaining a sliding window, it is usually necessary to consider whether the maximum or minimum value in the current queue expires.

`````` 1 #include <iostream>
2 #include <algorithm>
3 #include <deque>
4
5 using namespace std;
6
7 void solve(){
8
9     int N, K;
10     cin >> N >> K;
11     deque<int > Min;
12     deque<int > Max;
13     vector<int > ans;
14     vector<int > arr(N);
15     for(auto& it : arr) cin >> it;
16     // for(auto x : arr) cout << x << " ";
17     // cout << endl;
18     //Pressing a subscript can index the value of an array
19     for(int i = 0; i < N; ++i){
20         while(!Min.empty() && arr[Min.back()] >= arr[i]) Min.pop_back();
21         while(!Max.empty() && arr[Max.back()] <= arr[i]) Max.pop_back();
22         Min.push_back(i);
23         Max.push_back(i);
24         if(i >= K - 1){
25             while(!Min.empty() && Min.front() + K - 1 < i ) Min.pop_front(); //Minimum expired
26             while(!Max.empty() && Max.front() + K - 1 < i ) Max.pop_front(); //Maximum expired
27             if(Min.empty() || Max.empty()) cout << "error" << endl;
28             ans.push_back(arr[Max.front()]);
29             ans.push_back(arr[Min.front()]);
30         }
31     }
32     for(auto x : ans) cout << x << " ";
33     cout << endl;
34     for(auto x : ans) cout << x << " ";
35     cout << endl;
36 }
37
38 int main(){
39
40     ios::sync_with_stdio(false);
41     cin.tie(0);
42     cout.tie(0);
43     solve();
44
45     return 0;
46 }``````

Topics: less iOS