Leetcode Sliding Window Maximum

Tags: , ,

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 thek 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.

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

You may assume k is always valid, ie: 1 ≤ k ≤ input array’s size for non-empty array.

Follow up:
Could you solve it in linear time?


  1. How about using a data structure such as deque (double-ended queue)?
  2. The queue size need not be the same as the window’s size.
  3. Remove redundant elements and the queue should store only elements that need to be considered.


It is easy to come up with a solution using heap or priority queue .  A better solution is using a dequeue as described in the hint.
A dequeue is a double ended queue; In Java we can use LinkedList to represent a dequeue as it support operations on both sides of the list. 

The algorithm is described as follows:

for i from 0 to nums.length;

  1. if the queue is not empty, and the head of the queue equals to i – k, remove the queue head
  2. while the queue is not empty, keep removing the end of the queue until nums[q.end()] is larger than num[i]
  3. add i to the end of the queue
  4. if (i – k + 1 >=0) append nums[q.first()] to the result list. 

See the following figure to better understand the process:

Maximum Element Sliding Window

We can see that, the numbers in the queue is sorted, and the head of the queue is the biggest number in the window. 

Java Solution: