Find the maximum element in every contiguous subarray of size .
Given an integer array nums and an integer k, consider every contiguous subarray of length k. For each window, return the largest value contained in that window.
Your task is to produce the sequence of window maximums in the same order the windows appear from left to right.
Input Format
- An integer array
nums - An integer
krepresenting the window size
Output Format
- Return an array where the -th element is the maximum of
nums[i .. i+k-1]
Constraints
- The array may contain duplicate values and negative values
- Aim for an efficient solution better than checking every window element-by-element
Example 1
Input
nums = [1,3,-1,-3,5,3,6,7], k = 3
Output
[3,3,5,5,6,7]
Explanation
The windows are [1,3,-1], [3,-1,-3], [-1,-3,5], [-3,5,3], [5,3,6], and [3,6,7]. Their maximums are 3, 3, 5, 5, 6, and 7.
Example 2
Input
nums = [4,2,12,11,-5], k = 2
Output
[4,12,12,11]
Explanation
The windows are [4,2], [2,12], [12,11], and [11,-5]. Their maximums are 4, 12, 12, and 11.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.