Given an array and an integer k , find the maximum for each and every contiguous sub array of size k.
Sample Input :
1 2 3 1 4 5 2 3 6
3 [ value of w ]
Sample Output :
3 3 4 5 5 5 6
分析:
A natural way most people would think is to try to maintain the queue size the same as the window's
size. Try to break away from this thought and try to think outside of the box. Removing redundant
elements and storing only elements that need to be considered in the queue is the key to achieve the
efficient O(n) solution below.
#include <queue>
using namespace std;
void Funtion(int* A, int n, int w, int* B)
{
deque<int> dq;
for (int i=0; i<w; i++)
{
while(!dq.empty() && (A[i] > A[dq.back()]))
{
dq.pop_back();
}
dq.push_back(i);
}
for (int i=w; i<n; i++)
{
B[i-w] = A[dq.front()];
while (!dq.empty() && (A[i] > A[dq.back()]))
{
dq.pop_back();
}
while (!dq.empty() && (dq.front() <= (i-w)))
{
dq.pop_front();
}
dq.push_back(i);
}
B[n-w] = A[dq.front()]; // need to save the max value int the last window
}
int main ( int argc, char *argv[] )
{
int A[] = {1, 2, 3, 1, 4, 5, 2, 3, 6};
int n = sizeof(A) / sizeof(A[0]);
cout << n << endl;
int w = 3;
int n_b = n - 3 + 1;
int* B = new int[n_b];
Funtion(A, n, w, B);
for (int i=0; i<n_b; i++)
printf("%d ", B[i]);
printf("\n");
return 0;
}
本文介绍了一种高效求解滑动窗口中最大值问题的算法,并提供了完整的C++实现代码。该算法通过维护一个双端队列来跟踪当前窗口内的最大元素,实现了O(n)的时间复杂度。

被折叠的 条评论
为什么被折叠?



