
Sliding Window Maximum (hard)
Problem Statement
You are given an array of integers nums, and integer k, size of the sliding window which moves from the very left to the very right in the array. In each window, you can have only k numbers, and the window moves one position right by each time.
Return the array containing the maximum element of each sliding window.
Examples
Example 1:
- Input: nums = [2, 1, 5, 1, 3, 2], k = 3
- Expected Output: [5, 5, 5, 3]
- Justification: Here, the window of size 3 moves across the array. The maximum values in each window are 5 (from [2, 1, 5]), 5 (from [1, 5, 1]), 5 (from [5, 1, 3]), and 3 (from [1, 3, 2]).
Example 2:
- Input: nums = [4, -2, -3, 4, 1], k = 2
- Expected Output: [4, -2, 4, 4]
- Justification: The maximum values in each window of size 2 are 4 (from [4, -2]), -2 (from [-2, -3]), 4 (from [-3, 4]), and 4 (from [4, 1]).
Example 3:
- Input: nums = [9, 7, 2, 4, 6], k = 4
- Expected Output: [9, 7]
- Justification: In this case, there are only two windows of size 4. The maximum value in the first window is 9 (from [9, 7, 2, 4]), and in the second window is 7 (from [7, 2, 4, 6]).
Constraints:
- 1 <= nums.length <= 10<sup>5</sup>
- -10<sup>4</sup> <= nums[i] <= 10<sup>4</sup>
- 1 <= k <= nums.length
Try it yourself
Try solving this question here:
Python3
Python3
. . . .
.....
.....
.....
Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory