HardArrayQueueSliding WindowHeap (Priority Queue)Monotonic Queue

1 approach, code in every language

Problem description

You are given an integer array nums and an integer k. Imagine a window of width k that starts at the leftmost end of the array and slides one position to the right at a time until it reaches the far end.

At every stopping point the window covers exactly k consecutive elements, and you can only see the values currently inside it. For each window position, determine the largest value it contains.

Return these maximums as an array, ordered from the first window to the last.

Example 1

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

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

Window [1,3,-1] -> 3, [3,-1,-3] -> 3, [-1,-3,5] -> 5, [-3,5,3] -> 5, [5,3,6] -> 6, [3,6,7] -> 7.

Example 2

Input: nums = [1], k = 1

Output: [1]

A single element forms the only window, so its maximum is itself.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= k <= nums.length

After the pattern

Now solve one you haven't seen.

Rolling Peak Readings is our own problem on the technique behind Sliding Window Maximum: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free