Menu
CoddyTech

Sliding Window Maximum

You get an array of integers nums and a window size k. A window covers k consecutive values. It starts at the left end of the array and moves one position to the right at a time, until its right edge sits on the last value.

Return an array with the largest value inside the window at each of its positions, from left to right. An array of length n has n-k+1 windows, so the result has n-k+1 values.

Function

maxSlidingWindow(nums: integer-array, k: integer) → integer-array
numsinteger-array
the array the window slides over
kinteger
the number of values in every window
Returnsinteger-array
the largest value of each window, from the leftmost window to the rightmost

Constraints

  • 1 ≤ k ≤ nums.length ≤ 2 × 104
  • -104 ≤ nums[i] ≤ 104
  • The result holds nums.length-k+1 values, one per window, in order from left to right.

Examples

Input
nums = [4, 2, 12, 3, 8, 5, 1]k = 3
Output
[12, 12, 12, 8, 8]
Explanation
12 sits inside the first three windows, [4, 2, 12], [2, 12, 3] and [12, 3, 8]. After it slides out, the windows [3, 8, 5] and [8, 5, 1] both have 8 as their largest value.

lock icon+15 hidden tests on Submit

challenge icon

Follow-up

Can you build a queue that supports adding a value at the back, removing the value at the front and reading its current maximum, each in O(1) amortized time?

Reset code
def maxSlidingWindow(nums, k):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

nums = [4, 2, 12, 3, 8, 5, 1]
k = 3

Expected

[12, 12, 12, 8, 8]