Menu
CoddyTech

Sliding Window Maximum

You get an array of integers nums and a window size k. A window of k consecutive values starts at the left end and moves right one position at a time, until its right edge sits on the last value. Return the largest value in the window at each position, from left to right: n-k+1 values for an array of length n.

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 is inside the first three windows, so each of them answers 12. After it slides out, [3, 8, 5] and [8, 5, 1] both have 8 as their largest value.
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 #1

Test #2

Test #3

Arguments

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

Expected Output

[12, 12, 12, 8, 8]