VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-of-minimum-elements-of-all-subarrays/

⇱ Sum of Subarray Minimums - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of Subarray Minimums

Last Updated : 4 Dec, 2025

Given an array arr[] of integers, find the sum of the minimum element of every possible subarray of array.

Examples:

Input: arr[] = [10, 20] 
Output: 40
Explanation: Subarrays are [10], [20], [10, 20]. 
Minimums are [10, 20, 10]. Sum is 40.

Input : arr[] = [1, 2, 3, 4] 
Output: 20
Explanation: Subarrays are [1], [2], [3], [4], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2, 3], [2, 3, 4], [3, 4].
Minimums are [1, 2, 3, 4, 1, 1, 1, 2, 2, 3]. Sum is 20.

[Naive Approach] By Explore all Possible Subarrays - O(n2) Time and O(1) Space

The idea is to consider every possible subarray of the given array. For each subarray, we determine the minimum element and add it to our running sum. By doing this for all subarrays, the final result will be the sum of all minimum elements across all subarrays.


Output
20

[Expected Approach 1] Using Stack - O(n) Time and O(n) Space

Assume every element is the minimum element. So, each element has a range where it remains the minimum on both the left and the right side.
Now, the question transforms into: for every element, find the range where it will be the minimum.

How to find the range?

  • If we keep expanding to the left while the current element is still the minimum, as soon as we encounter an element smaller than the current one, that marks the boundary of its left range.
  • Similarly, if we expand to the right, the moment we find a smaller element, that becomes the boundary of its right range.

How to Count Subarrays in the Range?

Number of subarrays where A[i] is minimum= L × R

And its total contribution to the answer is:

Contribution of arr[i]= arr[i]× L× R

The idea is to find the range using Next Smaller and Previous Smaller elements (with the help of a monotonic stack) where the current element remains the minimum. Once the range is known, the contribution of that element to the total sum is calculated as arr[i] × L × R.


Output
20

[Expected Approach 2] Using Dynamic Programming - O(n) Time and O(n) Space

The idea is to compute the index of the next smaller element to the right for each element using a monotonic stack (increasing stack). This helps us determine how far the current element remains the minimum in subarrays starting from its index.


Output
20
Comment