Maximum of all Subarrays of size k using set in C++ STL


In this tutorial, we will be discussing a program to get maximum of all subarrays of size k using set in C++ STL.

For this we will be provided with a array of size N and integer K. Our task is to get the maximum element in each K elements, add them up and print it out.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//returning sum of maximum elements
int maxOfSubarrays(int arr[], int n, int k){
   set<pair<int, int> > q;
   set<pair<int, int> >::reverse_iterator it;
   //inserting elements
   for (int i = 0; i < k; i++) {
      q.insert(pair<int, int>(arr[i], i));
   }
   int sum = 0;
   for (int j = 0; j < n - k + 1; j++) {
      it = q.rbegin();
      sum += it->first;
      q.erase(pair<int, int>(arr[j], j));
      q.insert(pair<int, int>(arr[j + k], j + k));
   }
   return sum;
}
int main(){
   int arr[] = { 4, 10, 54, 11, 8, 7, 9 };
   int K = 3;
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << maxOfSubarrays(arr, n, K);
   return 0;
}

Output

182

Updated on: 06-Apr-2020

184 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements