Sum of minimum and maximum elements of all subarrays of size k.

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.Â
Steps to implement-
- Initialize a variable sum with value 0 to store the final answer
- Run two loops to find all subarrays
- Simultaneously find the length of the subarray
- If there is any subarray of size k
- Then find its maximum and minimum element
- Then add that to the sum variable
- In the last print/return value stored in the sum variable
Code-
C++
// C++ program to find sum of all minimum and maximum// elements Of Sub-array Size k.#include <bits/stdc++.h>using namespace std;Â
// Returns sum of min and max element of all subarrays// of size kint SumOfKsubArray(int arr[], int N, int k){    // To store final answer    int sum = 0;Â
    // Find all subarray    for (int i = 0; i < N; i++) {        // To store length of subarray        int length = 0;        for (int j = i; j < N; j++) {            // Increment the length            length++;Â
            // When there is subarray of size k            if (length == k) {                // To store maximum and minimum element                int maxi = INT_MIN;                int mini = INT_MAX;Â
                for (int m = i; m <= j; m++) {                    // Find maximum and minimum element                    maxi = max(maxi, arr[m]);                    mini = min(mini, arr[m]);                }Â
                // Add maximum and minimum element in sum                sum += maxi + mini;            }        }    }    return sum;}Â
// Driver program to test above functionsint main(){Â Â Â Â int arr[] = { 2, 5, -1, 7, -3, -1, -2 };Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â Â Â Â int k = 3;Â Â Â Â cout << SumOfKsubArray(arr, N, k);Â Â Â Â return 0;} |
Java
// Java program to find sum of all minimum and maximum// elements Of Sub-array Size k.Â
import java.util.Arrays;Â
class GFG {    // Returns sum of min and max element of all subarrays    // of size k    static int SumOfKsubArray(int[] arr, int N, int k) {        // To store the final answer        int sum = 0;Â
        // Find all subarrays        for (int i = 0; i < N; i++) {            // To store the length of the subarray            int length = 0;            for (int j = i; j < N; j++) {                // Increment the length                length++;Â
                // When there is a subarray of size k                if (length == k) {                    // To store the maximum and minimum element                    int maxi = Integer.MIN_VALUE;                    int mini = Integer.MAX_VALUE;Â
                    for (int m = i; m <= j; m++) {                        // Find the maximum and minimum element                        maxi = Math.max(maxi, arr[m]);                        mini = Math.min(mini, arr[m]);                    }Â
                    // Add the maximum and minimum element to the sum                    sum += maxi + mini;                }            }        }        return sum;    }Â
    // Driver program to test above functions    public static void main(String[] args) {        int[] arr = {2, 5, -1, 7, -3, -1, -2};        int N = arr.length;        int k = 3;        System.out.println(SumOfKsubArray(arr, N, k));    }}//This code is contributed by Vishal Dhaygude |
Python
# Returns sum of min and max element of all subarrays# of size kdef sum_of_k_subarray(arr, N, k):    # To store final answer    sum = 0Â
    # Find all subarrays    for i in range(N):        # To store length of subarray        length = 0        for j in range(i, N):            # Increment the length            length += 1Â
            # When there is a subarray of size k            if length == k:                # To store maximum and minimum element                maxi = float('-inf')                mini = float('inf')Â
                for m in range(i, j + 1):                    # Find maximum and minimum element                    maxi = max(maxi, arr[m])                    mini = min(mini, arr[m])Â
                # Add maximum and minimum element to sum                sum += maxi + mini    return sumÂ
# Driver program to test above functiondef main():Â Â Â Â arr = [2, 5, -1, 7, -3, -1, -2]Â Â Â Â N = len(arr)Â Â Â Â k = 3Â Â Â Â print(sum_of_k_subarray(arr, N, k))Â
if __name__ == "__main__":Â Â Â Â main() |
C#
using System;Â
class Program {    // Returns sum of min and max element of all subarrays    // of size k    static int SumOfKSubArray(int[] arr, int N, int k)    {        // To store the final answer        int sum = 0;Â
        // Find all subarrays        for (int i = 0; i < N; i++) {            // To store the length of subarray            int length = 0;            for (int j = i; j < N; j++) {                // Increment the length                length++;Â
                // When there is a subarray of size k                if (length == k) {                    // To store the maximum and minimum                    // element                    int maxi = int.MinValue;                    int mini = int.MaxValue;Â
                    for (int m = i; m <= j; m++) {                        // Find maximum and minimum element                        maxi = Math.Max(maxi, arr[m]);                        mini = Math.Min(mini, arr[m]);                    }Â
                    // Add maximum and minimum element in                    // sum                    sum += maxi + mini;                }            }        }        return sum;    }Â
    // Driver program to test above functions    static void Main()    {        int[] arr = { 2, 5, -1, 7, -3, -1, -2 };        int N = arr.Length;        int k = 3;        Console.WriteLine(SumOfKSubArray(arr, N, k));    }} |
Javascript
// JavaScript program to find sum of all minimum and maximum// elements of sub-array size k.Â
// Returns sum of min and max element of all subarrays// of size kfunction SumOfKsubArray(arr, N, k) {    // To store final answer    let sum = 0;Â
    // Find all subarray    for (let i = 0; i < N; i++) {        // To store length of subarray        let length = 0;        for (let j = i; j < N; j++) {            // Increment the length            length++;Â
            // When there is subarray of size k            if (length === k) {                // To store maximum and minimum element                let maxi = Number.MIN_SAFE_INTEGER;                let mini = Number.MAX_SAFE_INTEGER;Â
                for (let m = i; m <= j; m++) {                    // Find maximum and minimum element                    maxi = Math.max(maxi, arr[m]);                    mini = Math.min(mini, arr[m]);                }Â
                // Add maximum and minimum element in sum                sum += maxi + mini;            }        }    }    return sum;}Â
// Driver program to test above functionconst arr = [2, 5, -1, 7, -3, -1, -2];const N = arr.length;const k = 3;console.log(SumOfKsubArray(arr, N, k)); |
14
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 (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.Â
a) In deque 'G', we maintain decreasing order of
values from front to rear
b) In deque 'S', we maintain increasing order of
values from front to rear
1) First window size K
1.1) For deque 'G', if current element is greater
than rear end element, we remove rear while
current is greater.
1.2) For deque 'S', if current element is smaller
than rear end element, we just pop it while
current is smaller.
1.3) insert current element in both deque 'G' 'S'
2) After step 1, front of 'G' contains maximum element
of first window and front of 'S' contains minimum
element of first window. Remaining elements of G
and S may store maximum/minimum for subsequent
windows.
3) After that we do traversal for rest array elements.
3.1) Front element of deque 'G' is greatest and 'S'
is smallest element of previous window
3.2) Remove all elements which are out of this
window [remove element at front of queue ]
3.3) Repeat steps 1.1 , 1.2 ,1.3
4) Return sum of minimum and maximum element of all
sub-array size k.
Below is implementation of above ideaÂ
C++
// C++ program to find sum of all minimum and maximum// elements Of Sub-array Size k.#include<bits/stdc++.h>using namespace std;Â
// Returns sum of min and max element of all subarrays// of size kint SumOfKsubArray(int arr[] , int n , int k){Â Â Â Â int sum = 0;Â // Initialize resultÂ
    // The queue will store indexes of useful elements    // in every window    // In deque 'G' we maintain decreasing order of    // values from front to rear    // In deque 'S' we maintain increasing order of    // values from front to rear    deque< int > S(k), G(k);Â
    // Process first window of size K    int i = 0;    for (i = 0; i < k; i++)    {        // Remove all previous greater elements        // that are useless.        while ( (!S.empty()) && arr[S.back()] >= arr[i])            S.pop_back(); // Remove from rearÂ
        // Remove all previous smaller that are elements        // are useless.        while ( (!G.empty()) && arr[G.back()] <= arr[i])            G.pop_back(); // Remove from rearÂ
        // Add current element at rear of both deque        G.push_back(i);        S.push_back(i);    }Â
    // Process rest of the Array elements    for ( ; i < n; i++ )    {        // Element at the front of the deque 'G' & 'S'        // is the largest and smallest        // element of previous window respectively        sum += arr[S.front()] + arr[G.front()];Â
        // Remove all elements which are out of this        // window        while ( !S.empty() && S.front() <= i - k)            S.pop_front();        while ( !G.empty() && G.front() <= i - k)            G.pop_front();Â
        // remove all previous greater element that are        // useless        while ( (!S.empty()) && arr[S.back()] >= arr[i])            S.pop_back(); // Remove from rearÂ
        // remove all previous smaller that are elements        // are useless        while ( (!G.empty()) && arr[G.back()] <= arr[i])            G.pop_back(); // Remove from rearÂ
        // Add current element at rear of both deque        G.push_back(i);        S.push_back(i);    }Â
    // Sum of minimum and maximum element of last window    sum += arr[S.front()] + arr[G.front()];Â
    return sum;}Â
// Driver program to test above functionsint main(){Â Â Â Â int arr[] = {2, 5, -1, 7, -3, -1, -2} ;Â Â Â Â int n = sizeof(arr)/sizeof(arr[0]);Â Â Â Â int k = 3;Â Â Â Â cout << SumOfKsubArray(arr, n, k) ;Â Â Â Â return 0;} |
Java
// Java program to find sum of all minimum and maximum // elements Of Sub-array Size k. import java.util.Deque;import java.util.LinkedList;public class Geeks {Â
    // Returns sum of min and max element of all subarrays     // of size k     public static int SumOfKsubArray(int arr[] , int k)     {         int sum = 0; // Initialize result            // The queue will store indexes of useful elements         // in every window         // In deque 'G' we maintain decreasing order of         // values from front to rear         // In deque 'S' we maintain increasing order of         // values from front to rear         Deque<Integer> S=new LinkedList<>(),G=new LinkedList<>();Â
        // Process first window of size K         int i = 0;         for (i = 0; i < k; i++)         {             // Remove all previous greater elements             // that are useless.             while ( !S.isEmpty() && arr[S.peekLast()] >= arr[i])                 S.removeLast(); // Remove from rear                // Remove all previous smaller that are elements             // are useless.             while ( !G.isEmpty() && arr[G.peekLast()] <= arr[i])                 G.removeLast(); // Remove from rear                // Add current element at rear of both deque             G.addLast(i);             S.addLast(i);         }            // Process rest of the Array elements         for ( ; i < arr.length; i++ )         {             // Element at the front of the deque 'G' & 'S'             // is the largest and smallest             // element of previous window respectively             sum += arr[S.peekFirst()] + arr[G.peekFirst()];                // Remove all elements which are out of this             // window             while ( !S.isEmpty() && S.peekFirst() <= i - k)                 S.removeFirst();             while ( !G.isEmpty() && G.peekFirst() <= i - k)                 G.removeFirst();                // remove all previous greater element that are             // useless             while ( !S.isEmpty() && arr[S.peekLast()] >= arr[i])                 S.removeLast(); // Remove from rear                // remove all previous smaller that are elements             // are useless             while ( !G.isEmpty() && arr[G.peekLast()] <= arr[i])                 G.removeLast(); // Remove from rear                // Add current element at rear of both deque             G.addLast(i);             S.addLast(i);         }            // Sum of minimum and maximum element of last window         sum += arr[S.peekFirst()] + arr[G.peekFirst()];            return sum;     } Â
    public static void main(String args[])     {        int arr[] = {2, 5, -1, 7, -3, -1, -2} ;         int k = 3;         System.out.println(SumOfKsubArray(arr, k));    }}//This code is contributed by Gaurav Tiwari |
Python
# Python3 program to find Sum of all minimum and maximum # elements Of Sub-array Size k.from collections import dequeÂ
# Returns Sum of min and max element of all subarrays# of size kdef SumOfKsubArray(arr, n , k):Â
    Sum = 0 # Initialize resultÂ
    # The queue will store indexes of useful elements    # in every window    # In deque 'G' we maintain decreasing order of    # values from front to rear    # In deque 'S' we maintain increasing order of    # values from front to rear    S = deque()    G = deque()Â
Â
    # Process first window of size KÂ
    for i in range(k):                 # Remove all previous greater elements        # that are useless.        while ( len(S) > 0 and arr[S[-1]] >= arr[i]):            S.pop() # Remove from rearÂ
        # Remove all previous smaller that are elements        # are useless.        while ( len(G) > 0 and arr[G[-1]] <= arr[i]):            G.pop() # Remove from rearÂ
        # Add current element at rear of both deque        G.append(i)        S.append(i)Â
    # Process rest of the Array elements    for i in range(k, n):                 # Element at the front of the deque 'G' & 'S'        # is the largest and smallest        # element of previous window respectively        Sum += arr[S[0]] + arr[G[0]]Â
        # Remove all elements which are out of this        # window        while ( len(S) > 0 and S[0] <= i - k):            S.popleft()        while ( len(G) > 0 and G[0] <= i - k):            G.popleft()Â
        # remove all previous greater element that are        # useless        while ( len(S) > 0 and arr[S[-1]] >= arr[i]):            S.pop() # Remove from rearÂ
        # remove all previous smaller that are elements        # are useless        while ( len(G) > 0 and arr[G[-1]] <= arr[i]):            G.pop() # Remove from rearÂ
        # Add current element at rear of both deque        G.append(i)        S.append(i)Â
    # Sum of minimum and maximum element of last window    Sum += arr[S[0]] + arr[G[0]]Â
    return SumÂ
# Driver program to test above functionsarr=[2, 5, -1, 7, -3, -1, -2]n = len(arr)k = 3print(SumOfKsubArray(arr, n, k))Â
# This code is contributed by mohit kumar |
C#
// C# program to find sum of all minimum and maximum // elements Of Sub-array Size k. using System;using System.Collections.Generic;class Geeks{Â
  // Returns sum of min and max element of all subarrays   // of size k   public static int SumOfKsubArray(int []arr , int k)   {     int sum = 0; // Initialize result Â
    // The queue will store indexes of useful elements     // in every window     // In deque 'G' we maintain decreasing order of     // values from front to rear     // In deque 'S' we maintain increasing order of     // values from front to rear     List<int> S = new List<int>();    List<int> G = new List<int>();Â
    // Process first window of size K     int i = 0;     for (i = 0; i < k; i++)     { Â
      // Remove all previous greater elements       // that are useless.       while ( S.Count != 0 && arr[S[S.Count - 1]] >= arr[i])         S.RemoveAt(S.Count - 1); // Remove from rear Â
      // Remove all previous smaller that are elements       // are useless.       while ( G.Count != 0 && arr[G[G.Count - 1]] <= arr[i])         G.RemoveAt(G.Count - 1); // Remove from rear Â
      // Add current element at rear of both deque       G.Add(i);       S.Add(i);     } Â
    // Process rest of the Array elements     for ( ; i < arr.Length; i++ )     { Â
      // Element at the front of the deque 'G' & 'S'       // is the largest and smallest       // element of previous window respectively       sum += arr[S[0]] + arr[G[0]]; Â
      // Remove all elements which are out of this       // window       while ( S.Count != 0 && S[0] <= i - k)         S.RemoveAt(0);       while ( G.Count != 0 && G[0] <= i - k)         G.RemoveAt(0); Â
      // remove all previous greater element that are       // useless       while ( S.Count != 0 && arr[S[S.Count-1]] >= arr[i])         S.RemoveAt(S.Count - 1 ); // Remove from rear Â
      // remove all previous smaller that are elements       // are useless       while ( G.Count != 0 && arr[G[G.Count - 1]] <= arr[i])         G.RemoveAt(G.Count - 1); // Remove from rear Â
      // Add current element at rear of both deque       G.Add(i);       S.Add(i);     } Â
    // Sum of minimum and maximum element of last window     sum += arr[S[0]] + arr[G[0]];      return sum;   } Â
  // Driver code  public static void Main(String []args)   {    int []arr = {2, 5, -1, 7, -3, -1, -2} ;     int k = 3;     Console.WriteLine(SumOfKsubArray(arr, k));  }}Â
// This code is contributed by gauravrajput1 |
Javascript
<script>Â
// JavaScript program to find sum of all minimum and maximum// elements Of Sub-array Size k.Â
Â
// Returns sum of min and max element of all subarrays// of size kfunction SumOfKsubArray(arr , k){Â Â Â Â let sum = 0; // Initialize resultÂ
    // The queue will store indexes of useful elements    // in every window    // In deque 'G' we maintain decreasing order of    // values from front to rear    // In deque 'S' we maintain increasing order of    // values from front to rear    let S = [];    let G = [];Â
    // Process first window of size K    let i = 0;    for (i = 0; i < k; i++)    {Â
    // Remove all previous greater elements    // that are useless.    while ( S.length != 0 && arr[S[S.length - 1]] >= arr[i])        S.pop(); // Remove from rearÂ
    // Remove all previous smaller that are elements    // are useless.    while ( G.length != 0 && arr[G[G.length - 1]] <= arr[i])        G.pop(); // Remove from rearÂ
    // Add current element at rear of both deque    G.push(i);    S.push(i);    }Â
    // Process rest of the Array elements    for ( ; i < arr.length; i++ )    {Â
    // Element at the front of the deque 'G' & 'S'    // is the largest and smallest    // element of previous window respectively    sum += arr[S[0]] + arr[G[0]];Â
    // Remove all elements which are out of this    // window    while ( S.length != 0 && S[0] <= i - k)        S.shift(0);    while ( G.length != 0 && G[0] <= i - k)        G.shift(0);Â
    // remove all previous greater element that are    // useless    while ( S.length != 0 && arr[S[S.length-1]] >= arr[i])        S.pop(); // Remove from rearÂ
    // remove all previous smaller that are elements    // are useless    while ( G.length != 0 && arr[G[G.length - 1]] <= arr[i])        G.pop(); // Remove from rearÂ
    // Add current element at rear of both deque    G.push(i);    S.push(i);    }Â
    // Sum of minimum and maximum element of last window    sum += arr[S[0]] + arr[G[0]];    return sum;}Â
// Driver codeÂ
    let arr = [2, 5, -1, 7, -3, -1, -2];    let k = 3;    document.write(SumOfKsubArray(arr, k));Â
// This code is contributed by _saurabh_jaiswalÂ
</script> |
14
Time Complexity: O(n)
Auxiliary Space: O(k)
This article is contributed by Nishant_Singh (Pintu). If you like zambiatek and would like to contribute, you can also write an article using write.zambiatek.com or mail your article to review-team@zambiatek.com. See your article appearing on the zambiatek main page and help other Geeks.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



