Deque-STL

  • + 0 comments

    include

    include

    using namespace std;

    void printKMax(int arr[], int n, int k){ // //Write your code here. // int i = 0; // int j = k-1; // while(jmaxi) maxi = arr[k]; // } // cout< dq;

    // Process the first 'k' elements.
    for (int i = 0; i < k; i++) {
        // Remove elements smaller than the current one.
        while (!dq.empty() && arr[i] >= arr[dq.back()]) {
            dq.pop_back();
        }
        dq.push_back(i);
    }
    
    // Process the remaining elements.
    for (int i = k; i < n; i++) {
        // The front of the deque is the largest element of the previous window.
        cout << arr[dq.front()] << " ";
    
        // Remove elements that are out of this window.
        while (!dq.empty() && dq.front() <= i - k) {
            dq.pop_front();
        }
    
        // Remove elements smaller than the current one.
        while (!dq.empty() && arr[i] >= arr[dq.back()]) {
            dq.pop_back();
        }
    
        dq.push_back(i);
    }
    
    // Print the maximum of the last window.
    cout << arr[dq.front()] << endl;
    

    }

    int main(){

    int t;
    cin >> t;
    while(t>0) {
        int n,k;
        cin >> n >> k;
        int i;
        int arr[n];
        for(i=0;i<n;i++)
            cin >> arr[i];
        printKMax(arr, n, k);
        t--;
    }
    return 0;
    

    }