-
Notifications
You must be signed in to change notification settings - Fork 127
/
Sliding Window Maximum-239
74 lines (59 loc) · 1.71 KB
/
Sliding Window Maximum-239
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
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define MOD 1000000007
#define boost ios_base::sync_with_stdio(false);cin.tie(NULL);
// Problem Statement
// You are given an array of integers nums,
// there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window.
// Each time the sliding window moves right by one position.
// Return the max sliding window.
vector<int>maximuminwindow(int a[], int k,int n)
{
// a- given vector
deque<int>dq;
// we will be using deque to push and pop from both
// sides
// n- size of vector a
// k-window size
for(int i=0;i<k;i++)
{
while(!dq.empty()&&a[dq.back()]<=a[i])
{
dq.pop_back();
// remove the element form back
}
dq.push_back(i);
}
vector<int>v;
// v to store the final answer
for(int i=k;i<n;i++)
{
v.push_back(a[dq.front()]);
while(!dq.empty()&&dq.front()<=i-k)
{
dq.pop_front();
}
while(!dq.empty()&&a[dq.back()]<=a[i])
{
dq.pop_back();
}
dq.push_back(i);
}
v.push_back(a[dq.front()]);
return v;
}
int main(){
boost
int n=8;
int a[n]={1,3,-1,-3,5,3,6,7};
int k=3;
vector<int>v=maximuminwindow(a,k,n);
for(int i=0;i<v.size();i++)
{
cout<<v[i]<<" ";
}
// output will be 3 3 5 5 6 7
// time complexity- O(n)
// space complexity- O(n)
}