Maximum Of all subarrays of size K, using double ended queue

时间:2015-06-15 14:51:13

标签: algorithm data-structures queue

I have googled and found a solution for this,

void maxSlidingWindow(int A[], int n, int w, int B[]) {
  deque<int> Q;
  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()];
    while (!Q.empty() && A[i] >= A[Q.back()])
      Q.pop_back();
    while (!Q.empty() && Q.front() <= i-w)
      Q.pop_front();
    Q.push_back(i);
  }
  B[n-w] = A[Q.front()];
}

But I couldn't get this solution. For example, if you take the example {10,5,3,2} After the first for loop, the Dequeue will be like this, 3(rear)->5->10(head). When this comes to the second for loop 10 is saved in B[0]. , and the list will be like this, 2(rear)-> 3 -> 5 -> 10(head).

But, here '5' should be at front. Could someone please explain this code with an example.

1 个答案:

答案 0 :(得分:0)

您似乎错过了这个条件:Q.front() <= i-w 删除太旧前端项目。

您还可以查看我的评论in this answer