239. Sliding Window Maximum

Difficulty:
Related Topics:
Similar Questions:

Problem

You are given an array of integers 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.

Return the max sliding window.

  Example 1:

Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation: 
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

Example 2:

Input: nums = [1], k = 1
Output: [1]

  Constraints:

Solution 1

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
var maxSlidingWindow = function(nums, k) {
    // corner case
    if (nums === null || nums.length === 0) {
       return [0];
    }
    // normal case
    let queue = [];
    let res = new Array(nums.length + 1 - k);
    for (let i = 0; i < nums.length; i++) {
        if (queue.length && queue[0] === i - k) {
            queue.shift();
        }
        while (queue.length && nums[queue[queue.length - 1]] < nums[i]) {
            queue.pop();
        }
        queue.push(i);
        if (i + 1 - k >= 0) {
            res[i + 1 - k] = nums[queue[0]];
        }
    }
    return res;
};

Solution (python)

class Solution(object):
    def maxSlidingWindow(self, nums, k):
        q = deque()
        result = []

        for i in range(len(nums)):
            # the first/left (max) element is out of the current window
            if q and i - q[0] == k:
                q.popleft()

            while q:
                # pop useles elements from last of the queue
                if nums[q[-1]] < nums[i]:
                    q.pop()
                else:
                    break

            q.append(i)

            if i >= k - 1:
                result.append(nums[q[0]])

        return result

Solution (Java)

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        int n = nums.length;
        int[] res = new int[n - k + 1];
        int x = 0;
        LinkedList<Integer> dq = new LinkedList<>();
        int i = 0;
        int j = 0;
        while (j < nums.length) {
            while (!dq.isEmpty() && dq.peekLast() < nums[j]) {
                dq.pollLast();
            }
            dq.addLast(nums[j]);
            if (j - i + 1 == k) {
                res[x] = dq.peekFirst();
                ++x;
                if (dq.peekFirst() == nums[i]) {
                    dq.pollFirst();
                }
                ++i;
            }
            ++j;
        }
        return res;
    }
}

Explain:

nope.

Complexity: