Queries with Fixed Length

  • + 0 comments

    C++ implementation using a modified add/pop operation in deque :

    void add(deque<int>& q, int v){
        while(!q.empty() && q.back() < v) q.pop_back();
        q.push_back(v);      
    }
    
    int getMax(deque<int>& q){ return q.front(); }
    
    void pop(deque<int>& q, int rv){
        if(!q.empty() && rv == q.front()) q.pop_front();
    }
    
    int computeMinOfSubarrays(vector<int> maxs){
        int ans = INT_MAX;
        for(auto m : maxs) ans = min(ans, m);
        return ans;    
    }
    
    vector<int> solve(vector<int> arr, vector<int> queries) {
       vector<int> mins;
       for(auto subArrayLength : queries){
           deque<int> q; vector<int> maxs; 
           int size = 0;
           int toBeRemoved = 0;
           for(int i=0; i<arr.size(); ++i){
               add(q, arr[i]);
               size++;
               if(size == subArrayLength){
                   size -= 1;
                   maxs.push_back(getMax(q));
                   pop(q, arr[toBeRemoved++]);
               }
           }
           mins.push_back(computeMinOfSubarrays(maxs));
       } 
       return mins; 
    }