forked from meghasharma123/java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SlidingWindow.java
61 lines (38 loc) · 1.09 KB
/
SlidingWindow.java
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
import java.util.Deque;
import java.util.LinkedList;
public class Slidingwindow {
public static void main(String[] args) {
Solution solution= new Solution();
int a[]= {4,3,1,2,5,3,4,7,1,9};
int ans[]= solution.maxSlidingWindow(a, 4);
for(int x:ans) {
System.out.print(x+" ");
}
}
static class Solution {
public int[] maxSlidingWindow(int[] a, int k) {
int n= a.length;
Deque<Integer>dq=new LinkedList<>();
int ans[]=new int[n-k+1];
int i=0;
for(;i<k;i++) {
while(!dq.isEmpty()&& a[dq.peekLast()]<=a[i]) {
dq.removeLast();
}
dq.addLast(i);
}
for(;i<n;i++) {
ans[i-k]=a[dq.peekFirst()];
while(!dq.isEmpty() && dq.peekFirst()<=i-k) {
dq.removeFirst();
}
while(!dq.isEmpty()&& a[dq.peekLast()]<=a[i]) {
dq.removeLast();
}
dq.addLast(i);
}
ans[i-k]=a[ dq.peekFirst()];
return ans;
}
}
}