Sliding window max using deque
Java
Medium
6 views
Problem Description
Task: for each window of size k, return max. Use deque of indices.
Output Format
Return value
Official Solution
static int[] slidingMax(int[] a,int k){if(k<=0||a.length==0) return new int[0];int n=a.length;int[] res=new int[Math.max(0,n-k+1)];java.util.ArrayDeque<Integer> dq=new java.util.ArrayDeque<>();for(int i=0;i<n;i++){while(!dq.isEmpty() && dq.peekFirst()<=i-k) dq.removeFirst();while(!dq.isEmpty() && a[dq.peekLast()]<=a[i]) dq.removeLast();dq.addLast(i);if(i>=k-1) res[i-k+1]=a[dq.peekFirst()];}return res;}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!