-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_126sliding.java
More file actions
37 lines (35 loc) · 987 Bytes
/
_126sliding.java
File metadata and controls
37 lines (35 loc) · 987 Bytes
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
import java.util.*;
public class _126sliding {
static class Pair implements Comparable<Pair>{
int val;
int idx;
public Pair(int val,int idx){
this.val=val;
this.idx=idx;
}
@Override
public int compareTo(Pair p2){
return p2.val-this.val;
}
}
public static void main(String[] args) {
int arr[]={1,3,-1,-3,5,3,6,7};
int k=3;
int res[]=new int[arr.length-k+1];
PriorityQueue<Pair> pq = new PriorityQueue<>();
for(int i=0;i<k;i++){
pq.add(new Pair(arr[i],i));
}
res[0]=pq.peek().val;
for(int i =k; i<arr.length;i++){
while(pq.size()>0 && pq.peek().idx<= (i-k)){
pq.remove();
}
pq.add(new Pair(arr[i],i));
res[i-k+1] = pq.peek().val;
}
for(int i = 0; i<res.length;i++){
System.out.print(res[i]+ " ");
}
}
}