How to find maximum of each subarray of some fixed given length in a given array

后端 未结 6 1789
天涯浪人
天涯浪人 2021-02-14 16:41

We are given an array of n elements and an integer k. Suppose that we want to slide a window of length k across the array, reporting the largest value contained in each window.

6条回答
  •  -上瘾入骨i
    2021-02-14 17:00

    This older question discusses how to build a queue data structure supporting insert, dequeue, and find-min all in O(1) time. Note that this is not a standard priority queue, but instead is a queue in which at any point you can find the value of the smallest element it contains in O(1) time. You could easily modify this structure to support find-max in O(1) instead of find-min, since that's more relevant to this particular problem.

    Using this structure, you can solve this problem in O(n) time as follows:

    1. Enqueue the first k elements of the array into the special queue.
    2. For each element in the rest of the array:
      1. Use the queue's find-max operation to report the largest element of the current subrange.
      2. Dequeue an element from the queue, leaving the last k-1 elements of the old range in place.
      3. Enqueue the next element from the sequence, causing the queue to now hold the next k-element subrange of the sequence.

    This takes a total of O(n) time, since you visit each array element once, enqueuing and dequeuing each at most once, and calling find-max exactly n-k times. I think this is pretty cool, since the complexity is independent of k, which doesn't initially seem like it necessarily should be possible.

    Hope this helps! And thanks for asking a cool question!

提交回复
热议问题