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

后端 未结 6 1785
天涯浪人
天涯浪人 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条回答
  •  一生所求
    2021-02-14 17:13

    The best I can come up with quickly is O(n log m). You can get that by dynamic programming.

    In the first pass you find max for every element the maximum from the element itself and the next.

    Now you have n maximums (window size = 2).

    Now you can find on this array the maximum from every element and the overnext in this array (gives you for each element the maximum for the next 4, ie window size = 4).

    Then you can do it again, and again (and every time the window size doubles).

    As one clearly sees the window size grows exponentially.

    Therefor the runtime is O(n log m). The implementation is a bit tricky, because you must consider the corner and special cases (esp. when the windows size should not be a power of two), but they didnt influence the asymptotic runtime.

提交回复
热议问题