*w*which is moving from the very left of the array to the very right. You can only see the

*w*numbers in the window. Each time the sliding window moves rightwards by one position. Produce an array B[], B[i] is the maximum value of from A[i] to A[i+w-1]

Solution

- a naive solution is O(n w)

- an heap based solution could be O( n lg w), but we need to change the heap for maintaining n-w max positions and invalidate when the windows move. too complicated and not sure we can make it

- we can maintain a queue or better a dequeue while processing the array. The size of the queue Q is w and the key observation is that when we see an element A[j] we can remove each element in Q such that A[j] > Q[z] because we are looking for the max and those elements are not max given the esistence of A[j]. In doing so, we keep the current maximum at front and we remove the other elements from the back of the deque. Each element will enter 1 time in the queue and will exit at most 1 time, so the total complexity is O(n) which is pretty good. For keeping the sliding window we push current Array index so we need to remove from front when out of current window

- #include
- void maxSlidingWindow(int A[], int n, int w, int B[])
- {
- deque<int> Q;
- //Initilize deque Q for first window
- for (int i = 0; i < w; i++)
- {
- while (!Q.empty() && A[i] >= A[Q.back()])
- Q.pop_back();
- Q.push_back(i);
- }
- for (int i = w; i < n; i++)
- {
- B[i-w] = A[Q.front()];
- //update Q for new window
- while (!Q.empty() && A[i] >= A[Q.back()])
- Q.pop_back();
- //Pop older element outside window from Q
- while (!Q.empty() && Q.front() <= i-w)
- Q.pop_front();
- //Insert current element in Q
- Q.push_back(i);
- }
- B[n-w] = A[Q.front()];
- }

## No comments:

## Post a Comment