LeetCode-in-All

239. Sliding Window Maximum

Hard

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

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
var maxSlidingWindow = function (nums, k) {
    let dq = []
    let i = 0, j = 0
    let res = []

    while (j < nums.length) {
        if (dq.length === 0) {
            dq.push(j)
        } else {
            while (dq.length !== 0 && nums[dq[dq.length - 1]] <= nums[j]) {
                dq.pop()
            }
            dq.push(j)
        }
        if ((j - i + 1) === k) {
            res.push(nums[dq[0]])
            if (dq[0] === i) {
                dq.shift()
            }
            i++
        }
        j++
    }
    return res 
};

export { maxSlidingWindow }