![]() |
VOOZH | about |
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.
Table of Content
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.
20
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?
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.
20
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.
20