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

后端 未结 6 1814
天涯浪人
天涯浪人 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:20

    You can keep a Binary Search Tree of the current elements, for example, save them as value-occurrence pairs. Other than that, you sliding window algorithm should be good enough.

    This way, select maximum (the max element in the subsection) will cost O(logL) time, L being the length of the current subsection; add new would also be O(logL). TO delete the oldest one, just search the value and decrements the count by 1, if the count goes to 0 delete it.

    So the total time will be O(NlogL), N being the length of the array.

提交回复
热议问题