C++ program to find maximum of each k sized contiguous subarray

Suppose we have an array with n elements and a value k. We shall have to find maximum value for each of the contiguous subarray of size k.

So, if the input is like arr = [3,4,6,2,8], k = 3, then the output will be The contiguous subarrays of size 3 are [3,4,6], [4,6,2], [6,2,8], so the maximum elements are 6, 6 and 8.

To solve this, we will follow these steps −

  • Define one deque Qi of size k
  • for initialize i := 0, when i
  • while Qi is not empty and arr[i] >= arr[last element of Qi], do:
    • delete last element from Qi
  • insert i at the end of Qi
  • for i
  • display arr[first element of Qi]
  • while Qi is not empty and first element of Qi
  • delete front element from Qi
  • while Qi is not empty and arr[i] >= arr[last element of Qi], do:
    • delete last element from Qi
  • insert i at the end of Qi
  • display arr[first element of Qi]
  • Example

    Let us see the following implementation to get better understanding −

    #include <iostream>
    #include <vector>
    #include <deque>
    using namespace std;
    int main(){
       vector<int> arr = {3,4,6,2,8};
       int k = 3;
       deque<int> Qi(k);
       int i;
       for (i = 0; i < k; ++i){
          while ( (!Qi.empty()) && arr[i] >= arr[Qi.back()])
             Qi.pop_back();
    
             Qi.push_back(i);
         }
         for ( ; i < arr.size(); ++i){
            cout << arr[Qi.front()] << " ";
            while ( (!Qi.empty()) && Qi.front() <= i - k)
                Qi.pop_front();
            while ( (!Qi.empty()) && arr[i] >= arr[Qi.back()])
                Qi.pop_back();
            Qi.push_back(i);
        }
        cout << arr[Qi.front()] << endl;
    }
    

    Input

    {3,4,6,2,8}, 3

    Output

    6 6 8
    Updated on: 2021-10-07T08:42:37+05:30

    504 Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements