Sliding Window Maximum
Given an integer array nums and a window size k, the window of k consecutive elements slides from the left end to the right end one position at a time. Return an array of the maximum value inside the window at each position.
Open official problem prompt ↗Produce the maximum of every contiguous block of k elements as the block slides across the array, in linear total time.
Think of people queued by height at a viewpoint. Whenever a taller person arrives, everyone shorter behind them steps aside because they will be blocked from view for as long as the tall person stays. The tallest still in the viewing zone stands at the front.
- Input
- nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
- Output
- [3, 3, 5, 5, 6, 7]
- Why
- The successive windows are [1,3,-1], [3,-1,-3], [-1,-3,5], [-3,5,3], [5,3,6], [3,6,7], whose maxima are 3,3,5,5,6,7.
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^41 <= k <= nums.length