Queries with Fixed Length

  • + 0 comments

    linear time with sliding window

    int solve(const vector<int>& arr, int d) {
        deque<int> dQ;
        vector<int> slidingWindow;
        for (int i = 0; i < arr.size(); ++i) {
            if (!dQ.empty() and dQ.front() == i - d) dQ.pop_front();
            while (!dQ.empty() and arr[dQ.back()] <= arr[i]) dQ.pop_back();
            dQ.push_back(i);
            if (i >= d - 1) slidingWindow.push_back(arr[dQ.front()]);
        }
        return *min_element(slidingWindow.begin(), slidingWindow.end());
    }