VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-minimum-maximum-elements-subarrays-size-k/

⇱ Sum of min and max of all subarrays of size k. - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of min and max of all subarrays of size k.

Last Updated : 7 Sep, 2025

Given an array of both positive and negative integers, the task is to compute sum of minimum and maximum elements of all sub-array of size k.

Examples: 

Input : arr[] = {2, 5, -1, 7, -3, -1, -2}
K = 4
Output : 18
Explanation : Subarrays of size 4 are :
{2, 5, -1, 7}, min + max = -1 + 7 = 6
{5, -1, 7, -3}, min + max = -3 + 7 = 4
{-1, 7, -3, -1}, min + max = -3 + 7 = 4
{7, -3, -1, -2}, min + max = -3 + 7 = 4

Missing sub arrays -

{2, -1, 7, -3}
{2, 7, -3, -1}
{2, -3, -1, -2}
{5, 7, -3, -1}
{5, -3, -1, -2}
and few more -- why these were not considered??
Considering missing arrays result coming as 27

Sum of all min & max = 6 + 4 + 4 + 4 = 18

This problem is mainly an extension of below problem. 
Maximum of all subarrays of size k 

Naive Approach:

Run two loops to generate all subarrays and then choose all subarrays of size k and find maximum and minimum values. Finally, return the sum of all maximum and minimum elements. 


Output
18

Time Complexity: O(N2*k), because two loops to find all subarray and one loop to find the maximum and minimum elements in the subarray of size k
Auxiliary Space: O(1), because no extra space has been used

Method 2 (Using MultiSet):

The idea is to use Multiset data structure and sliding window concept.

  • Firstly, We create a multiset of pair of {number,index}, because index would help us in removing the ith element and move to next window of size k.
  • Secondly, we have i and j which are back and front pointer used to maintain a window.
  • Traverse through the array and insert into multiset pair of {number,index}, and also check for windowSize, once it becomes equals to k, start your primary goal, i.e. to find sum of max & min elements.
  • Then erase the ith index number from the set and move the ith pointer to next location , i.e. new window of size k.

Implementation:


Output
18

Time Complexity: O(nlogk)
Auxiliary Space: O(k)

Method 3 (Efficient using Dequeue):

The idea is to use Dequeue data structure and sliding window concept. We create two empty double-ended queues of size k ('S' , 'G') that only store indices of elements of current window that are not useless. An element is useless if it can not be maximum or minimum of next subarrays. 


Output
18

Time Complexity: O(n)
Auxiliary Space: O(k)

Comment
Article Tags: