Queries with Fixed Length

  • + 0 comments
    from collections import deque
    
    def min_of_max_in_subarrays_with_size(d, arr):
        # use sliding window to iterate through array
        dq = deque()
        candidtaes = []
        for i in range(len(arr)):
            # remove out-of-window index
            if dq and dq[0] <= i-d:
                dq.popleft()
            # before adding the current index, make sure to remove all indexes
            # indicating to value not larger than that of the current i
            # this way can make sure the maximum is in the front of queue
            while dq and arr[dq[-1]] <= arr[i]:
                dq.pop()
            dq.append(i)
            # add to max subarrays
            if i >= d-1:
                candidtaes.append(arr[dq[0]])
        return min(candidtaes)
    
    def solve(arr, queries):
        result = []  # the min of max subarrays with size d
        for d in queries:
            result.append(min_of_max_in_subarrays_with_size(d, arr))
        return result