 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements
 