
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Sum of Minimum and Maximum Elements of All Subarrays of Size K
In this problem, we need to take the maximum and minimum elements of all sub?array of length K and add them to get the answer.
The first solution approach is that traverse through all sub?arrays of size K, find the minimum and maximum element of each sub?array, and add them. The optimized approach to solve the problem is using the deque data structure. We will store the index of the minimum and maximum elements of the subarray in the deque.
Problem statement ? We have given an array nums[] containing N positive or negative integer values. We have also given the positive integer 0 < K < N. We need to sum the maximum and minimum elements of all subarrays of size K.
Sample examples
Input
nums[] = {3, 5, ?2, 6, 4, 8, ?9, 10, ?5}, K = 4
Output
15
Explanation ? Here, we have given each sub-array minimum and maximum elements.
[3, 5, ?2, 6] ? min_ele = ?2, max_ele = 6 ?> min_ele + max_ele = 4
[5, ?2, 6, 4] ? min_ele = ?2, max_ele = 6 ?> min_ele + max_ele = 4
[?2, 6, 4, 8] ? min_ele = ?2, max_ele = 8 ?> min_ele + max_ele = 6
[6, 4, 8, ?9] ? min_ele = ?9, max_ele = 8 ?> min_ele + max_ele = ?1
[4, 8, ?9, 10] ? min_ele = ?9, max_ele = 10 ?> min_ele + max_ele = 1
[8, ?9, 10, ?5}, ? min_ele = ?9, max_ele = 10 ?> min_ele + max_ele = 1
So, total sum is 4 + 4 + 6 + ?1 + 1 + 1 is 15.
Input
nums[] = {3, 5, ?2, 6, 4, 8, ?9, 10, ?5}, K = 9
Output
1
Explanation ? The K is equal to the size of the array. So, we can sum the minimum and maximum element of the given array, which is ?9 and 10, respectively.
Input
nums[] = {2, 7, ?9}, K = 1
Output
0
Explanation ? The value of the K is 1. So, we can add each element two times in sum.
Approach 1
In this approach, we will use two nested loops to get all subarrays of length K and find the minimum and maximum element of the subarray. After that, we will add minimum and maximum elements of all subarrays to the resultant variable.
Algorithm
Step 1? Initialize the ?ans' with 0 to store the resultant sum value.
Step 2? Start traversing the given array, and initialize the ?m' variable with 0 to track the length of the subarray. Also, initialize the ?max_ele' variable with the minimum integer value and the ?min_ele' variable with the maximum integer value.
Step 3? Use a nested loop to traverse the array from the pth index.
Step 3.1? Increment the ?m' value by 1.
Step 3.2? Use the max() function to get the maximum from the nums[q] and max_ele element. Also, use the min() function to get the minimum from the nums[q] and min_ele element.
Step 3.3? If m is equal to K, add the value of the max_ele and min_ele to the ?ans' variable's value, and break the nested loop using the break keyword.
Step 4? Return ?ans' at the end of the function.
Example
#include <bits/stdc++.h> using namespace std; int subArrSum(int nums[], int len, int K) { // To store the resultant ans int ans = 0; // Get a subarray of size K for (int p = 0; p < len; p++) { int m = 0; // For storing the minimum and maximum element of the subarray int max_ele = INT_MIN; int min_ele = INT_MAX; for (int q = p; q < len; q++) { m++; max_ele = max(max_ele, nums[q]); min_ele = min(min_ele, nums[q]); // When we get a subarray of length K if (m == K) { ans += max_ele + min_ele; break; } } } return ans; } int main() { int nums[] = {3, 5, -2, 6, 4, 8, -9, 10, -5}; int len = sizeof(nums) / sizeof(nums[0]); int K = 4; cout << "The ans of minimum and maximum elements of all subarrays of size K is " << subArrSum(nums, len, K); return 0; }
Output
The ans of minimum and maximum elements of all subarrays of size K is 15
Time complexity ? O(N*K), as we traverse all subarrays of length K.
Space complexity ? O(1) as we use the constant space.
Approach 2
In this approach, we will use the deque data structure to solve the problem. We will create two different deques to track the index of the maximum and minimum elements of the current subarray.
Algorithm
Step 1? Initialize the ?totalSum' variable with 0 to store the resultant sum.
Step 2? Define the ?inc' and ?dec' deque of size K to track the subarray elements' indexes. The ?inc' deque will be used to store the index of array elements according to the increasing value of subarray elements, and the ?dec' deque will store the index of array elements according to the decreasing value of subarray elements.
Step 3? Now, initialize the ?p' with 0, and we need to process the first subarray of the length K.
Step 4? Traverse the first subarray of the length K.
Step 4.1? In the loop, use the while loop to remove elements from the ?inc' deque if the queue is not empty and the element present at the inc.back() index in the array is greater than the element present at the pth index.
Step 4.2? Sameway, remove the elements from the back of the ?dec' deque if the element present at the dec.back() index in the array is smaller than the element present at the pth index.
Step 4.3? Push the p into the ?inc' and ?dec' deque.
Step 5? We need to process the other subarrays of length K.
Step 5.1? Access the first index value from the ?inc' and ?dec' deque, get the element value from the array according to their first index, and add them to the ?totalSum' value.
Step 5.2? If any index is present at the start of the ?inc' and ?dec' deque is not in the current window, pop it from the deque.
Step 5.3? Again, follow steps 4.1 and 4.2 for other subarrays.
Step 5.4? Push the p into both deques.
Step 6? Handle the sum of the minimum and maximum elements of the last window.
Step 7? Return the ?totalSum' value.
Example
#include <bits/stdc++.h> using namespace std; int subArrSum(int nums[], int len, int k){ int totalSum = 0; // Deques to store indices of the current window in increasing and decreasing order, respectively; deque<int> inc(k), dec(k); // Handling the first window int p = 0; for (p = 0; p < k; p++){ // Remove elements which are greater than the current element while ((!inc.empty()) && nums[inc.back()] >= nums[p]) inc.pop_back(); // Remove elements from dec deque which are smaller than the current element while ((!dec.empty()) && nums[dec.back()] <= nums[p]) dec.pop_back(); // Remove from rear // Add the nums[p] at last inc.push_back(p); dec.push_back(p); } // Hanlding other windows for (; p < len; p++){ // get the first element from both the queues, and add them totalSum += nums[inc.front()] + nums[dec.front()]; // Removing elements of the previous window while (!inc.empty() && inc.front() <= p - k) inc.pop_front(); while (!dec.empty() && dec.front() <= p - k) dec.pop_front(); while ((!inc.empty()) && nums[inc.back()] >= nums[p]) inc.pop_back(); while ((!dec.empty()) && nums[dec.back()] <= nums[p]) dec.pop_back(); inc.push_back(p); dec.push_back(p); } // Last window sum totalSum += nums[inc.front()] + nums[dec.front()]; return totalSum; } int main() { int nums[] = {3, 5, -2, 6, 4, 8, -9, 10, -5}; int len = sizeof(nums) / sizeof(nums[0]); int K = 4; cout << "The ans of minimum and maximum elements of all subarrays of size K is " << subArrSum(nums, len, K); return 0; }
Output
The ans of minimum and maximum elements of all subarrays of size K is 15
Time complexity ? O(N + K), to traverse the array.
Space complexity ? O(K) to store the indexes in the deque.
The second approach is more optimized in the manner of time complexity. However, it takes more space than the first approach. Programmers may use any approach according to the given number of elements. For small inputs, the first approach is suitable, and for large inputs, the second approach is suitable.