Original link: leetcode-cn.com/problems/sl…

Answer:

Intuitive JavaScript Solution with Monotonic Queue

  1. Each time a window is slid, the value moved out of the window is removed from the queue
  2. Queuing the newly entered value and removing any element smaller than the moved value ensures that the queue is sorted from largest to smallest.
  3. The first value of the queue is always the maximum value in the current window, which is stored into the result array each time through the loop.
/ * * *@param {number[]} nums
 * @param {number} k
 * @return {number[]}* /
var maxSlidingWindow = function (nums, k) {
  let result = [];
  let dequeue = [];

  for (let i = 0; i < nums.length; i++) {
    // When the window slides, check whether the front element of the queue is not in the window, if so, remove it
    if (nums[i - k] === dequeue[0]) {
      dequeue.shift();
    }
    // If there is a value in the queue, all values in the queue less than the current value are emptied. Make sure the queue is arranged from large to small.
    while (dequeue.length && nums[i] > dequeue[dequeue.length - 1]) {
      dequeue.pop();
    }

    // Queue the newly entered window value.
    dequeue.push(nums[i]);

    // Start storing results when the window is full
    if (i >= k - 1) {
      // The first value of the current queue is always the maximum value of the current slider, which can be directly saved to the result
      result.push(dequeue[0]); }}return result;
};
Copy the code