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++
#include <bits/stdc++.h>
using namespace std;
int SumOfKsubArray( int arr[], int N, int k)
{
int sum = 0;
for ( int i = 0; i < N; i++) {
int length = 0;
for ( int j = i; j < N; j++) {
length++;
if (length == k) {
int maxi = INT_MIN;
int mini = INT_MAX;
for ( int m = i; m <= j; m++) {
maxi = max(maxi, arr[m]);
mini = min(mini, arr[m]);
}
sum += maxi + mini;
}
}
}
return sum;
}
int 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
import java.util.Arrays;
class GFG {
static int SumOfKsubArray( int [] arr, int N, int k) {
int sum = 0 ;
for ( int i = 0 ; i < N; i++) {
int length = 0 ;
for ( int j = i; j < N; j++) {
length++;
if (length == k) {
int maxi = Integer.MIN_VALUE;
int mini = Integer.MAX_VALUE;
for ( int m = i; m <= j; m++) {
maxi = Math.max(maxi, arr[m]);
mini = Math.min(mini, arr[m]);
}
sum += maxi + mini;
}
}
}
return sum;
}
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));
}
}
|
Python
def sum_of_k_subarray(arr, N, k):
sum = 0
for i in range (N):
length = 0
for j in range (i, N):
length + = 1
if length = = k:
maxi = float ( '-inf' )
mini = float ( 'inf' )
for m in range (i, j + 1 ):
maxi = max (maxi, arr[m])
mini = min (mini, arr[m])
sum + = maxi + mini
return sum
def 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 {
static int SumOfKSubArray( int [] arr, int N, int k)
{
int sum = 0;
for ( int i = 0; i < N; i++) {
int length = 0;
for ( int j = i; j < N; j++) {
length++;
if (length == k) {
int maxi = int .MinValue;
int mini = int .MaxValue;
for ( int m = i; m <= j; m++) {
maxi = Math.Max(maxi, arr[m]);
mini = Math.Min(mini, arr[m]);
}
sum += maxi + mini;
}
}
}
return sum;
}
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
function SumOfKsubArray(arr, N, k) {
let sum = 0;
for (let i = 0; i < N; i++) {
let length = 0;
for (let j = i; j < N; j++) {
length++;
if (length === k) {
let maxi = Number.MIN_SAFE_INTEGER;
let mini = Number.MAX_SAFE_INTEGER;
for (let m = i; m <= j; m++) {
maxi = Math.max(maxi, arr[m]);
mini = Math.min(mini, arr[m]);
}
sum += maxi + mini;
}
}
}
return sum;
}
const arr = [2, 5, -1, 7, -3, -1, -2];
const N = arr.length;
const k = 3;
console.log(SumOfKsubArray(arr, N, k));
|
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++
#include<bits/stdc++.h>
using namespace std;
int SumOfKsubArray( int arr[] , int n , int k)
{
int sum = 0;
deque< int > S(k), G(k);
int i = 0;
for (i = 0; i < k; i++)
{
while ( (!S.empty()) && arr[S.back()] >= arr[i])
S.pop_back();
while ( (!G.empty()) && arr[G.back()] <= arr[i])
G.pop_back();
G.push_back(i);
S.push_back(i);
}
for ( ; i < n; i++ )
{
sum += arr[S.front()] + arr[G.front()];
while ( !S.empty() && S.front() <= i - k)
S.pop_front();
while ( !G.empty() && G.front() <= i - k)
G.pop_front();
while ( (!S.empty()) && arr[S.back()] >= arr[i])
S.pop_back();
while ( (!G.empty()) && arr[G.back()] <= arr[i])
G.pop_back();
G.push_back(i);
S.push_back(i);
}
sum += arr[S.front()] + arr[G.front()];
return sum;
}
int 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
import java.util.Deque;
import java.util.LinkedList;
public class Geeks {
public static int SumOfKsubArray( int arr[] , int k)
{
int sum = 0 ;
Deque<Integer> S= new LinkedList<>(),G= new LinkedList<>();
int i = 0 ;
for (i = 0 ; i < k; i++)
{
while ( !S.isEmpty() && arr[S.peekLast()] >= arr[i])
S.removeLast();
while ( !G.isEmpty() && arr[G.peekLast()] <= arr[i])
G.removeLast();
G.addLast(i);
S.addLast(i);
}
for ( ; i < arr.length; i++ )
{
sum += arr[S.peekFirst()] + arr[G.peekFirst()];
while ( !S.isEmpty() && S.peekFirst() <= i - k)
S.removeFirst();
while ( !G.isEmpty() && G.peekFirst() <= i - k)
G.removeFirst();
while ( !S.isEmpty() && arr[S.peekLast()] >= arr[i])
S.removeLast();
while ( !G.isEmpty() && arr[G.peekLast()] <= arr[i])
G.removeLast();
G.addLast(i);
S.addLast(i);
}
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));
}
}
|
Python
from collections import deque
def SumOfKsubArray(arr, n , k):
Sum = 0
S = deque()
G = deque()
for i in range (k):
while ( len (S) > 0 and arr[S[ - 1 ]] > = arr[i]):
S.pop()
while ( len (G) > 0 and arr[G[ - 1 ]] < = arr[i]):
G.pop()
G.append(i)
S.append(i)
for i in range (k, n):
Sum + = arr[S[ 0 ]] + arr[G[ 0 ]]
while ( len (S) > 0 and S[ 0 ] < = i - k):
S.popleft()
while ( len (G) > 0 and G[ 0 ] < = i - k):
G.popleft()
while ( len (S) > 0 and arr[S[ - 1 ]] > = arr[i]):
S.pop()
while ( len (G) > 0 and arr[G[ - 1 ]] < = arr[i]):
G.pop()
G.append(i)
S.append(i)
Sum + = arr[S[ 0 ]] + arr[G[ 0 ]]
return Sum
arr = [ 2 , 5 , - 1 , 7 , - 3 , - 1 , - 2 ]
n = len (arr)
k = 3
print (SumOfKsubArray(arr, n, k))
|
C#
using System;
using System.Collections.Generic;
class Geeks
{
public static int SumOfKsubArray( int []arr , int k)
{
int sum = 0;
List< int > S = new List< int >();
List< int > G = new List< int >();
int i = 0;
for (i = 0; i < k; i++)
{
while ( S.Count != 0 && arr[S[S.Count - 1]] >= arr[i])
S.RemoveAt(S.Count - 1);
while ( G.Count != 0 && arr[G[G.Count - 1]] <= arr[i])
G.RemoveAt(G.Count - 1);
G.Add(i);
S.Add(i);
}
for ( ; i < arr.Length; i++ )
{
sum += arr[S[0]] + arr[G[0]];
while ( S.Count != 0 && S[0] <= i - k)
S.RemoveAt(0);
while ( G.Count != 0 && G[0] <= i - k)
G.RemoveAt(0);
while ( S.Count != 0 && arr[S[S.Count-1]] >= arr[i])
S.RemoveAt(S.Count - 1 );
while ( G.Count != 0 && arr[G[G.Count - 1]] <= arr[i])
G.RemoveAt(G.Count - 1);
G.Add(i);
S.Add(i);
}
sum += arr[S[0]] + arr[G[0]];
return sum;
}
public static void Main(String []args)
{
int []arr = {2, 5, -1, 7, -3, -1, -2} ;
int k = 3;
Console.WriteLine(SumOfKsubArray(arr, k));
}
}
|
Javascript
<script>
function SumOfKsubArray(arr , k)
{
let sum = 0;
let S = [];
let G = [];
let i = 0;
for (i = 0; i < k; i++)
{
while ( S.length != 0 && arr[S[S.length - 1]] >= arr[i])
S.pop();
while ( G.length != 0 && arr[G[G.length - 1]] <= arr[i])
G.pop();
G.push(i);
S.push(i);
}
for ( ; i < arr.length; i++ )
{
sum += arr[S[0]] + arr[G[0]];
while ( S.length != 0 && S[0] <= i - k)
S.shift(0);
while ( G.length != 0 && G[0] <= i - k)
G.shift(0);
while ( S.length != 0 && arr[S[S.length-1]] >= arr[i])
S.pop();
while ( G.length != 0 && arr[G[G.length - 1]] <= arr[i])
G.pop();
G.push(i);
S.push(i);
}
sum += arr[S[0]] + arr[G[0]];
return sum;
}
let arr = [2, 5, -1, 7, -3, -1, -2];
let k = 3;
document.write(SumOfKsubArray(arr, k));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(k)
This article is contributed by Nishant_Singh (Pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.