Given an array 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.

For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

1
2
3
4
5
6
7
8
Window position                Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7

Therefore, return the max sliding window as [3,3,5,5,6,7].

O(n log k) O(k) space heap solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums == null || nums.length < 1) return new int[0];
int[] result = new int[nums.length - k + 1];
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(k, (a, b) -> b - a);
for (int i = 0; i <= k - 1; i++) {
pq.offer(nums[i]);
}
result[0] = pq.peek();
int left = 1, right = k;
for (int j = 1; j < result.length; j++) {
pq.remove(new Integer(nums[left - 1]));
pq.offer(nums[right]);
result[j] = pq.peek();
right++;
left++;
}
return result;
}
}

O(n) time O(k) space deque solution

public class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums == null || nums.length < 1) return new int[0];
        int[] res = new int[nums.length - k + 1];
        int resIndex = 0;
        Deque<Integer> deque = new LinkedList<>();
        for (int i = 0; i < nums.length; i++) {
            while (!deque.isEmpty() && deque.peek() < i - k + 1) {
                deque.poll();
            }
            while(!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) {
                deque.pollLast();
            } 
            deque.offer(i);
            if (i >= k - 1) {
                res[resIndex++] = nums[deque.peek()];
            }
        }
        return res;
    }
}