Queries with Fixed Length

  • + 0 comments

    Python, using heapq (a little troublesome since it is implemented using min heap instead of max heap) and dictionary for counting

    def solve(arr, queries):
        arr = [-1 * elem for elem in arr]
        answers = []
        for q in queries:
            subarray = arr[:q]
            heapify(subarray)
            valuecounter = defaultdict(lambda: 0)
            for elem in subarray:
                valuecounter[elem] += 1
            curmax = subarray[0]
            minofmax = curmax
            for index in range(q, len(arr)):
                newvalue = arr[index]
                oldvalue = arr[index - q]
                valuecounter[newvalue] += 1
                valuecounter[oldvalue] -= 1
                heappush(subarray, newvalue)
                while True:
                    curmax = subarray[0]
                    if valuecounter[curmax] != 0:
                        break
                    else:
                        heappop(subarray)
                minofmax = max(minofmax, curmax)
            answers.append(-1 * minofmax)
        return answers