Max-heap with lazy removal
Time O(n log n) Space O(n)Push (value, index) into a max-heap. For each window, pop from the top while the top's index has left the window, then read the top.
import java.util.PriorityQueue;
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> b[0] != a[0] ? Integer.compare(b[0], a[0]) : Integer.compare(b[1], a[1]));
int[] out = new int[nums.length - k + 1];
for (int i = 0; i < nums.length; i++) {
heap.offer(new int[]{nums[i], i});
if (i >= k - 1) {
while (heap.peek()[1] <= i - k) heap.poll();
out[i - k + 1] = heap.peek()[0];
}
}
return out;
}
}Verdict: Works, but the deque is faster.