Example 1
- Input
- nums = [1,3,-1,-3,5,3,6,7], k = 3
- Output
- [3,3,5,5,6,7]
Each of the 6 windows contributes its maximum: 3, 3, 5, 5, 6, 7.
Given an integer array and a window size k, slide a fixed window across the array one step at a time and return the maximum element inside each position of the window.
You are given an array of integers nums, and there is a sliding window of size k which moves from the very left of the array to the very right. You can only see the k numbers in the window, and the window moves right by one position each time.
Return the maximum of each window position. For nums = [1,3,-1,-3,5,3,6,7] with k = 3 the windows are [1,3,-1], [3,-1,-3], [-1,-3,5], [-3,5,3], [5,3,6], [3,6,7], so the answer is [3,3,5,5,6,7].
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^41 <= k <= nums.lengthEach of the 6 windows contributes its maximum: 3, 3, 5, 5, 6, 7.
There is a single window holding the only element.
Windows [4,4], [4,-1], and [-1,-2] have maxima 4, 4, and -1. The duplicate maxima occupy different indices and expire separately; the final negative-only window must not produce zero.
A window contains k consecutive positions, and each output is the largest value in those positions. In Example 1, value 3 remains the maximum for the first two windows. Keeping only the last maximum fails when it expires: we need other candidates. A deque is a queue that permits removal at either end. Keep candidate indices ordered from oldest to newest, with values non-increasing from front to back. A newer larger value permanently makes older smaller candidates unnecessary, because the newer value expires later.
Reveal Brute Force: intuition, complexity, and code
k elements repeats nearly the whole job.For fixed windows needing an extremum, discard candidates dominated by newer values and expire indices by position. A monotonic deque preserves just enough history to answer each window in one linear scan; storing indices makes value order and window membership separate checks.