Maximum Number within Window
Medium
Given an integer array A and a sliding window of size K, find the maximum value of each window as it slides from left to right.
Assumptions
The given array is not null and is not empty
K >= 1, K <= A.length
Examples
A = {1, 2, 3, 2, 4, 2, 1}, K = 3, the windows are {{1,2,3}, {2,3,2}, {3,2,4}, {2,4,2}, {4,2,1}},
and the maximum values of each K-sized sliding window are [3, 3, 4, 4, 4]
Solution: Descending deque to maintain greatest number in current window
top of the deque will always be the greatest
it can be replaced in two ways:
it is outside of the window. PollFirst()
A greater number has been discovered. PollLast()
When new number enters. He must first remove all elements lesser than him, because he will be dominant until he exits the queue.
TC: O(N) Every index goes in to the queue only once
SC: O(K) k elements in queue at max. ex: k = 3, Front { 9, 8 ,7 } Back
Last updated
Was this helpful?