Maximum of all Subarrays of size k using set in C++ STL
Last Updated :
23 Nov, 2022
Given an array of size N and an integer K, the task is to find the maximum for each and every contiguous sub-array of size K and print the sum of all these values in the end. Examples:
Input: arr[] = {4, 10, 54, 11, 8, 7, 9}, K = 3
Output: 182
Input: arr[] = {1, 2, 3, 4, 1, 6, 7, 8, 2, 1}, K = 4
Output: 45
Prerequisite:
Approach: Set performs insertion and removal operation in O(logK) time and always stores the keys in the sorted order. The idea is to use a set of pairs where the first item in the pair is the element itself and the second item in the pair contains the array index of the element.
- Pick first k elements and create a set of pair with these element and their index as described above.
- Now, set sum = 0 and use window sliding technique and Loop from j = 0 to n – k:
- Get the maximum element from the set (the last element) in the current window and update sum = sum + currMax.
- Search for the leftmost element of current window in the set and remove it.
- Insert the next element of the current window in the set to move to next window.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxOfSubarrays( int arr[], int n, int k)
{
set<pair< int , int > > q;
set<pair< int , int > >::reverse_iterator it;
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;
}
|
Complexity Analysis:
- Time Complexity: O(n Log n)
- Auxiliary Space : O(k)
The above problem can be solved in O(n) time. Please see below Dequeue based solution for the same.
Sliding Window Maximum (Maximum of all subarrays of size k)
Share your thoughts in the comments
Please Login to comment...