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

后端 未结 6 1815
天涯浪人
天涯浪人 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 16:57

    You could proceed like a tabu search :

    Loop through the list and get the max of the 4 first ith element. Then on the next step just check if the i+1th element is superior to the max of the previous elements

    • if i+1>=previous max then new max = i+1 reinialise tabu
    • if i+1< previous max then if the previous max was found less than N step ago keep the previous (here is the tabu )
    • if i+1< preivous max and the previous max is tabu then take the new max of the 4 i+1th elements.

    I'm not sure it's clear but tell me if you have any question. below is a code in python to test it.

    l=[15,10,9,16,20,14,13,11,12]
    N=4
    res=[-1] #initialise res
    tabu=1  #initialise tabu
    for k in range(0,len(l)):
    #if the previous element res[-1] is higher than l[k] and not tabu then keep it
    #if the previous is tabu and higher than l[k] make a new search without it
    #if the previous is smaller than l[k] take the new max =l[k]
    
        if l[k]= res[-1]:
            tabu=1
            res.append(l[k])
    
    print res[N:] #take of the N first element
    

    Complexity:

    I updated the code thx to flolo and the complexity. it's not anymore O(N) but O(M*N)

    The worst case is when you need to recalculate a maximum at each step of the loop. i e a strictly decreasing list for example.

    at each step of the loop you need to recalculate the max of M elements

    then the overall complexity is O(M*N)

提交回复
热议问题