DevPath

← All problems

Sliding Window Maximum

Hard queue · arrays · sliding-window

Description

Return the maximum of every contiguous window of size k.

Constraints

1 <= k <= n <= 100000

Examples

Input: nums = [1,3,-1,-3,5,3,6,7], k = 3

Output: [3,3,5,5,6,7]

Hints (1)
  • Keep a deque of indices with decreasing values.

Solutions

Monotonic deque of indices. · Time O(n) · Space O(k)

func maxSlidingWindow(nums []int, k int) []int {
    dq := []int{}
    out := []int{}
    for i, n := range nums {
        if len(dq) > 0 && dq[0] <= i-k {
            dq = dq[1:]
        }
        for len(dq) > 0 && nums[dq[len(dq)-1]] <= n {
            dq = dq[:len(dq)-1]
        }
        dq = append(dq, i)
        if i >= k-1 {
            out = append(out, nums[dq[0]])
        }
    }
    return out
}

Create a free account to submit solutions, track progress and save problems.

Create account