Sliding Window Maximum I

A long array A[] is given to you. There is a sliding window of size 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. Following is an example:
The array is [1 3 -1 -3 5 3 6 7], and w is 3.

Window position Max
————— —–
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
Input: A long array A[], and a window width w
Output: An array B[], B[i] is the maximum value of from A[i] to A[i+w-1]
Requirement: Find a good optimal way to get B[i].

Idea: 1. Use max-heap to store the window data. Then it is easy to obtain the maximum.

Difficulty: How to eliminate data that is out of date. Although remove arbitrary element is O(log w) as well, we need to track the position of every element in the heap.

2. We could test if the max element is still valid for the next slot. If not, we should keep on pop data out until the max element is valid for the next slot. Although, there could be data which is out of data in the heap, it will not affect the output since we only get the maximum element in the heap.

C++:
01 typedef pair <int, int> Pair;
02 void maxWindowSlide(int A[], int n, int w, int B[])
03 {
04     priority_queue <Pair> Q;
05     for(int i=0;i<w;i++)
06         Q.push(Pair(A[i],i));
07     for(int i=w;i<n;i++){
08         Pair p=Q.top();
09         B[iw]=p.first;
10         while(p.second<=iw){
11             Q.pop();
12             p=Q.top();
13         }
14         Q.push(Pair(A[i],i));
15     }
16     B[nw]=Q.top().first;
17 }
Advertisements
This entry was posted in Heap. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s