Sliding Window Maximum using Deque in c++

 

Sliding Window Maximum is a common problem in computer science that involves finding the maximum element in a given window of a given size within an array. The problem can be solved using various algorithms, but one of the most efficient and popular methods is using a Deque (Double Ended Queue) in C++.

A Deque is a data structure that is similar to a Queue, but it allows for elements to be added and removed from both ends. This makes it an ideal data structure for solving the Sliding Window Maximum problem because it allows for quick insertion and deletion of elements.

The basic idea behind using a Deque for solving the Sliding Window Maximum problem is to maintain a Deque that contains the indices of the elements in the window in decreasing order of their values. This way, the first element in the Deque will always be the index of the maximum element in the window.

To implement this approach in C++, we first need to create a Deque and initialize it with the first few elements of the array. We then begin a loop that will iterate through the rest of the elements in the array. For each element, we first check if the Deque is empty or if the element at the front of the Deque is outside the window. If either of these conditions are true, we remove the element from the Deque.

Next, we compare the current element to the elements in the Deque. We remove any elements from the Deque that are smaller than the current element. This is because we only want to keep the maximum element in the window, so we remove any elements that are smaller than the current element.

Finally, we add the current element to the Deque and check if the Deque is empty or if the element at the front of the Deque is outside the window. If either of these conditions are true, we remove the element from the Deque.

The above steps can be implemented in C++ using the following code:

#include <iostream> 
 #include <deque> 
 using namespace std;
 void sliding_window_maximum(int arr[], int n, int k) {
 deque<int> dq;
 for (int i = 0; i < k; i++) {
 while (!dq.empty() && arr[i] >= arr[dq.back()]) { 
 dq.pop_back();
 } 
 dq.push_back(i);
 } 
 for (int i = k; i < n; i++) {
 cout << arr[dq.front()] << " "
 while (!dq.empty() && dq.front() <= i - k) {
 dq.pop_front();
 } 
 while (!dq.empty() && arr[i] >= arr[dq.back()]) {
 dq.pop_back();
 }
 dq.push_back(i);
 }
 cout << arr[dq.front()]; 
}

In the above code, the function "sliding_window_maximum" takes in an array "arr", the size of the array "n", and the size of the window "k" as its parameters. The first loop initializes the Deque with the first "k" elements of the array. The second loop iterates through the rest of the elements in the array and performs the steps described above.

It's worth noting that the time complexity of this algorithm is O(n) which is considered to be very efficient.

Sliding Window Maximum using Deque in c++