Queries with Fixed Length

  • + 0 comments

    Clean solution in C++

    vector<int> solve(vector<int> arr, vector<int> queries) {
        vector<int> res;
        int N = arr.size();
        for (int i = 0; i < queries.size(); i++) {
            int d = queries[i];
            vector<int> q;
            int mini = INT32_MAX; 
            for (int j = 0; j < N;j ++){ 
                // q is a decreasing vector
                while (!q.empty() && q.back() < arr[j]) {
                    q.pop_back();
                }
                q.push_back(arr[j]);
                if (j + 1 >= d) {
                    if (mini > q[0]) {
                        mini = q[0];
                    }
                    if (q[0] == arr[j+1-d]) {
                        q.erase(q.begin());
                    }
                }
            } 
            res.push_back(mini);
        }
        
        return res;
    }