
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Maximum subarray size, such that all subarrays of that size have sum less than k in C++
- Maximum subarray size, such that all subarrays of that size have sum less than k in C++ program
- Max sum of M non-overlapping subarrays of size K in C++
- Maximum sum two non-overlapping subarrays of given size in C++
- Maximum product of subsequence of size k in C++
- Product of all Subsequences of size K except the minimum and maximum Elements in C++
- Count of subarrays whose maximum element is greater than k in C++
- Maximum Unique Element in every subarray of size K in c++
- Count subarrays with all elements greater than K in C++
- Maximum sum of lengths of non-overlapping subarrays with k as the max element in C++
- Maximum Size Subarray Sum Equals k in C++
- Find the number of subarrays have bitwise OR >= K using C++
- Find maximum (or minimum) sum of a subarray of size k in C++
- Find Maximum XOR value of a sub-array of size k in C++
- Number of Subarrays with Bounded Maximum in C++

Advertisements