Leetcode 239: Sliding Window Maximum

https://leetcode.com/problems/sliding-window-maximum/

Sliding Window Maximum

Total Accepted: 13329 Total Submissions: 57131 Difficulty: Hard

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.

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

Note:
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?

 

Code

from collections import *
class Solution(object):
    def maxSlidingWindow(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        res = []
        # deque of (idx, val)
        q = deque()
        for i,v in enumerate(nums):
            while q and q[0][0] < i-(k-1):
                q.popleft()
            while q and q[-1][1] < v:
                q.pop()
            q.append((i, v))
            if i >= k-1:
                res.append(q[0][1])
        return res

 

Idea

An O(N) time complexity algorithm. Each element is appended to and popped out of the deque at most one time. Idea can be found here: https://leetcode.com/discuss/46578/java-o-n-solution-using-deque-with-explanation

Leave a comment

Your email address will not be published. Required fields are marked *