Sum of minimum elements of all possible sub-arrays of an array
Last Updated :
15 Sep, 2022
Given an array arr[], the task is to find the sum of the minimum elements of every possible sub-array of the array.
Examples:
Input: arr[] = {1, 3, 2}
Output: 15
All possible sub-arrays are {1}, {2}, {3}, {1, 3}, {3, 2} and {1, 3, 2}
And, the sum of all the minimum elements is 1 + 2 + 3 + 1 + 2 + 1 = 10
Input: arr[] = {3, 1}
Output: 5
A simple method is to generate all the sub-arrays and then sum the minimum elements in all of them. The time complexity of this solution will be O(n3).
Better method: The key for optimization is the question:
In how many segments, the value at an index will be minimum?
The next idea that might come into our mind will be for every index i in the array arr, we try to find:
Left count: We iterate towards the left of the index i till we don't encounter an element strictly lesser than arr[i] or we don't reach the left end of the array. Let us call this count for the index i of the given array as CLi.
Right count: We iterate towards the right of the index till we don't encounter an element less than or equal to the value at the index, or we don't reach the right end. Let us call this count for the index i of the given array as CRi.
(CLi + 1) * (CRi + 1) will be the number of sub-arrays for the current index i in which its value will be minimal because there are CLi + 1 ways to choose elements from the left side (including choosing no element) and CRi + 1 ways to choose elements from the right side.
The time complexity of this approach will be O(n2)
The Best method:
This problem can be solved using a stack data structure in O(n) time. The idea remains the same as is in the previous approach. For the sake of saving some time, we will use a stack from the Standard Template Library of C++.
Left count: Let CLi represent the left count for an index i. CLi for an index i can be defined as the number of elements between the index i and the right most element whose value is strictly less than arr[i] having index less than i. If, there is no such element, then CLi for an element will be equal to the number of elements to the left of the index i.
To achieve this, we will insert only the index of the elements from left to right into the stack. Let us suppose, we are inserting an index i in the stack and j be the index of the topmost element currently present in the stack. While the value arr[i] is less than or equal to the value at the topmost index in the stack and the stack is not empty, keep popping the elements in the stack. Whenever, an element is popped, the left count(CLi) of the current index(i) is updated as CLi = CLi + CLj + 1.
Right count: We calculate the right count for all the indexes similarly. The only difference is we push the elements in the stack while traversing right to left in the array. While arr[i] is strictly less than the value at the topmost index in the stack and the stack is not empty, keep popping the elements. Whenever, an element is popped, the right count of the current index(i) is updated as CRi = CRi + CRj + 1.
Final step: Let ans be the variable containing the final answer. We will initialize it with 0. Then, we will iterate through all the indexes from 1 to n of the array and update the ans as ans = ans + (CLi + 1) * (CRi + 1) * arr[i] for all possible values of i from 1 to n.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <iostream>
#include <stack>
using namespace std;
// Function to return the required sum
int findMinSum(int arr[], int n)
{
// Arrays for maintaining left and right count
int CL[n] = { 0 }, CR[n] = { 0 };
// Stack for storing the indexes
stack<int> q;
// Calculate left count for every index
for (int i = 0; i < n; i++) {
while (q.size() != 0 && arr[q.top()] >= arr[i]) {
CL[i] += CL[q.top()] + 1;
q.pop();
}
q.push(i);
}
// Clear the stack
while (q.size() != 0)
q.pop();
// Calculate right count for every index
for (int i = n - 1; i >= 0; i--) {
while (q.size() != 0 && arr[q.top()] > arr[i]) {
CR[i] += CR[q.top()] + 1;
q.pop();
}
q.push(i);
}
// Clear the stack
while (q.size() != 0)
q.pop();
// To store the required sum
int ans = 0;
// Calculate the final sum
for (int i = 0; i < n; i++)
ans += (CL[i] + 1) * (CR[i] + 1) * arr[i];
return ans;
}
// Driver code
int main()
{
int arr[] = { 1, 3, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findMinSum(arr, n);
}
Java
// Java implementation of the above approach
import java.util.*;
class GFG
{
// Function to return the required sum
static int findMinSum(int arr[], int n)
{
// Arrays for maintaining left and right count
int CL[] = new int[n], CR[] = new int[n];
// Stack for storing the indexes
Stack<Integer> q = new Stack<Integer>();
// Calculate left count for every index
for (int i = 0; i < n; i++)
{
while (q.size() != 0 && arr[q.peek()] >= arr[i])
{
CL[i] += CL[q.peek()] + 1;
q.pop();
}
q.push(i);
}
// Clear the stack
while (q.size() != 0)
q.pop();
// Calculate right count for every index
for (int i = n - 1; i >= 0; i--)
{
while (q.size() != 0 && arr[q.peek()] > arr[i])
{
CR[i] += CR[q.peek()] + 1;
q.pop();
}
q.push(i);
}
// Clear the stack
while (q.size() != 0)
q.pop();
// To store the required sum
int ans = 0;
// Calculate the final sum
for (int i = 0; i < n; i++)
ans += (CL[i] + 1) * (CR[i] + 1) * arr[i];
return ans;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 3, 2 };
int n = arr.length;
System.out.println(findMinSum(arr, n));
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 implementation of the approach
# Function to return the required sum
def findMinSum(arr, n):
# Arrays for maintaining left and
# right count
CL = [0] * n
CR = [0] * n
# Stack for storing the indexes
q = []
# Calculate left count for every index
for i in range(0, n):
while (len(q) != 0 and
arr[q[-1]] >= arr[i]):
CL[i] += CL[q[-1]] + 1
q.pop()
q.append(i)
# Clear the stack
while len(q) != 0:
q.pop()
# Calculate right count for every index
for i in range(n - 1, -1, -1):
while (len(q) != 0 and
arr[q[-1]] > arr[i]):
CR[i] += CR[q[-1]] + 1
q.pop()
q.append(i)
# Clear the stack
while len(q) != 0:
q.pop()
# To store the required sum
ans = 0
# Calculate the final sum
for i in range(0, n):
ans += (CL[i] + 1) * (CR[i] + 1) * arr[i]
return ans
# Driver code
if __name__ == "__main__":
arr = [1, 3, 2]
n = len(arr)
print(findMinSum(arr, n))
# This code is contributed by Rituraj Jain
C#
// C# implementation of the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to return the required sum
static int findMinSum(int []arr, int n)
{
// Arrays for maintaining left and right count
int []CL = new int[n];
int []CR = new int[n];
// Stack for storing the indexes
Stack<int> q = new Stack<int>();
// Calculate left count for every index
for (int i = 0; i < n; i++)
{
while (q.Count != 0 && arr[q.Peek()] >= arr[i])
{
CL[i] += CL[q.Peek()] + 1;
q.Pop();
}
q.Push(i);
}
// Clear the stack
while (q.Count != 0)
q.Pop();
// Calculate right count for every index
for (int i = n - 1; i >= 0; i--)
{
while (q.Count != 0 && arr[q.Peek()] > arr[i])
{
CR[i] += CR[q.Peek()] + 1;
q.Pop();
}
q.Push(i);
}
// Clear the stack
while (q.Count != 0)
q.Pop();
// To store the required sum
int ans = 0;
// Calculate the final sum
for (int i = 0; i < n; i++)
ans += (CL[i] + 1) * (CR[i] + 1) * arr[i];
return ans;
}
// Driver code
public static void Main(String[] args)
{
int []arr = { 1, 3, 2 };
int n = arr.Length;
Console.WriteLine(findMinSum(arr, n));
}
}
// This code has been contributed
// by 29AjayKumar
JavaScript
<script>
// Javascript implementation of the approach
// Function to return the required sum
function findMinSum(arr, n)
{
// Arrays for maintaining left and right count
var CL = Array(n).fill(0);
var CR = Array(n).fill(0);
// Stack for storing the indexes
var q = [];
// Calculate left count for every index
for (var i = 0; i < n; i++) {
while (q.length != 0 && arr[q[q.length-1]] >= arr[i]) {
CL[i] += CL[q[q.length-1]] + 1;
q.pop();
}
q.push(i);
}
// Clear the stack
while((q.length) != 0)
q.pop();
// Calculate right count for every index
for (var i = n - 1; i >= 0; i--) {
while (q.length != 0 && arr[q[q.length-1]] > arr[i]) {
CR[i] += CR[q[q.length-1]] + 1;
q.pop();
}
q.push(i);
}
// Clear the stack
while((q.length) != 0)
q.pop();
// To store the required sum
var ans = 0;
// Calculate the final sum
for (var i = 0; i < n; i++)
ans += (CL[i] + 1) * (CR[i] + 1) * arr[i];
return ans;
}
// Driver code
var arr = [1, 3, 2 ];
var n = arr.length;
document.write( findMinSum(arr, n));
</script>
Complexity Analysis:
- Time complexity: O(n)
- Auxiliary Space: O(n)
Similar Reads
Sum of Bitwise-OR of all subarrays of a given Array | Set 2
Give an array of positive integers. The task is to find the total sum after performing the bitwise OR operation on all the sub-arrays of the given array. Examples: Input : arr[] = {1, 2, 3, 4, 5} Output : 71 Input : arr[] = {6, 5, 4, 3, 2} Output : 84 Explanation: Simple Approach: A simple approach
12 min read
Longest unique subarray of an Array with maximum sum in another Array
Given two arrays X[] and Y[] of size N, the task is to find the longest subarray in X[] containing only unique values such that a subarray with similar indices in Y[] should have a maximum sum. The value of array elements is in the range [0, 1000]. Examples: Input: N = 5, X[] = {0, 1, 2, 0, 2}, Y[]
10 min read
Minimize insertions in an array to obtain all sums upto N
Given a sorted array arr[] of positive integers of size K, and an integer N. The task is to find the minimum number of elements to be inserted in this array, such that all positive integers in range [1, N] can be obtained as a sum of subsets of the modified array. Note: The array won't have any dupl
10 min read
Minimize the sum of the squares of the sum of elements of each group the array is divided into
Given an array consisting of even number of elements, the task is to divide the array into M group of elements (every group must contain at least 2 elements) such that the sum of the squares of the sums of each group is minimized i.e., (sum_of_elements_of_group1)2 + (sum_of_elements_of_group2)2 + (s
5 min read
Minimum MEX from all subarrays of length K
Given an array arr[] consisting of N distinct positive integers and an integer K, the task is to find the minimum MEX from all subarrays of length K. The MEX is the smallest positive integer that is not present in the array. Examples: Input: arr[] = {1, 2, 3}, K = 2Output: 1Explanation:All subarrays
7 min read
Minimum possible value T such that at most D Partitions of the Array having at most sum T is possible
Given an array arr[] consisting of N integers and an integer D, the task is to find the least integer T such that the entire array can be partitioned into at most D subarrays from the given array with sum atmost T. Examples: Input: D = 5, arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Output: 15 Explanatio
9 min read
Smallest element present in every subarray of all possible lengths
Given an array arr[] of length N, the task for every possible length of subarray is to find the smallest element present in every subarray of that length. Examples: Input: N = 10, arr[] = {2, 3, 5, 3, 2, 3, 1, 3, 2, 7}Output: -1-1 3 2 2 2 1 1 1 1Explanation:For length = 1, no element is common in ev
15+ min read
Minimize the maximum element of N subarrays of size K
Given an array arr[] and two integers N and K, the task is to choose non-overlapping N subarrays of size K such that the maximum element of all subarrays is minimum.Note: If it is not possible to choose N such subarrays then return -1. Examples: Input: arr[] = {1, 10, 3, 10, 2}, N = 3, K = 1 Output:
8 min read
Minimum count of numbers required from given array to represent S
Given an integer S and an array arr[], the task is to find the minimum number of elements whose sum is S, such that any element of the array can be chosen any number of times to get sum S. Examples: Input: arr[] = {25, 10, 5}, S = 30 Output: 2 Explanation: In the given array there are many possible
15+ min read
Count of subarrays of size K which is a permutation of numbers from 1 to K
Given an array arr of distinct integers, the task is to find the count of sub-arrays of size i having all elements from 1 to i, in other words, the sub-array is any permutation of elements from 1 to i, with 1 < = i <= N. Examples: Input: arr[] = {2, 3, 1, 5, 4} Output: 3 Explanation: we have {
6 min read