Given array \(\texttt{A[]}\) with sliding window of size \(\texttt{w}\) which is moving from the very left of the array to the very right. Assume that we can only see the \(\texttt{w}\) numbers in the window. Each time the sliding window moves rightwards by one position. For example: the array is \(\texttt{[1 3 -1 -3 5 3 6 7]}\), and \(\texttt{w}\) is 3.
\(\begin{array}{|l|c|} \hline
\textbf{Window position} & \textbf{Max} \\\hline
\texttt{[1 3 -1] -3 5 3 6 7} & 3 \\\hline
\texttt{1 [3 -1 -3] 5 3 6 7} & 3 \\\hline
\texttt{1 3 [-1 -3 5] 3 6 7} & 5 \\\hline
\texttt{1 3 -1 [-3 5 3] 6 7} & 5 \\\hline
\texttt{1 3 -1 -3 [5 3 6] 7} & 6 \\\hline
\texttt{1 3 -1 -3 5 [3 6 7]} & 7 \\\hline
\end{array}\)
Input: A long array \(\texttt{A[]}\), and a window width \(\texttt{w}\).
Output: An array \(\texttt{B[]}\), \(\texttt{B[i]}\) is the maximum value of from \(\texttt{A[i]}\) to \(\texttt{A[i+w-1]}\).
Requirement: Find a good optimal way to get \(\texttt{B[i]}\).
Difficulty level
Video recording
This exercise is mostly suitable for students
void MaxSlidingWindow(int A[], int n , int w, int B[])
{
Deque Q=CreateDeque();
int i;
element e;
for(i=0;i<w;i++)
{
while(!isEmptyDeque(Q) && Rear(Q,&e) && A[i]>=A[e])
deleteRear(&Q);
insertRear(&Q,i);
}
for(i=w; i<n;i++)
{
Front(Q,&e);
B[i-w]=A[e];
while(!isEmptyDeque(Q) && Rear(Q,&e) && A[i]>=A[e])
deleteRear(&Q);
while(!isEmptyDeque(Q) && Front(Q,&e) && e<=i-w)
deleteFront(&Q);
insertRear(&Q,i);
}
Front(Q,&e);
B[n-w]=A[e];
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Sorting using quick-sort algorithm