09. Sum of Subarray Minimums
β GFG solution to the Sum of Subarray Minimums problem: find the total sum of minimum elements in all subarrays using monotonic stack and contribution technique. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given an array arr[] of positive integers, find the total sum of the minimum elements of every possible subarrays.
A subarray is a contiguous sequence of elements within an array. For each subarray, we need to find its minimum element and sum all these minimum values.
π Examples
Example 1
Input: arr[] = [3, 1, 2, 4]
Output: 17
Explanation: Subarrays are [3], [1], [2], [4], [3, 1], [1, 2], [2, 4], [3, 1, 2], [1, 2, 4], [3, 1, 2, 4].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum of all these is 17.Example 2
Input: arr[] = [71, 55, 82, 55]
Output: 593
Explanation: The sum of the minimum of all the subarrays is 593.π Constraints
$1 \le \text{arr.size()} \le 3 \times 10^4$
$1 \le \text{arr}[i] \le 10^3$
β
My Approach
The optimal approach uses Monotonic Stack with Contribution Technique to efficiently calculate how many times each element contributes as a minimum in different subarrays:
Two-Pass Stack
Calculate Left Boundaries:
For each element at index
i, find how many elements to the left are greater than or equal toarr[i].Use a monotonic stack to find the nearest smaller element on the left.
left[i]represents the number of subarrays ending atiwherearr[i]is the minimum.
Calculate Right Boundaries:
For each element at index
i, find how many elements to the right are strictly greater thanarr[i].Use a monotonic stack to find the nearest smaller element on the right.
right[i]represents the number of subarrays starting atiwherearr[i]is the minimum.
Calculate Contribution:
For each element
arr[i], its total contribution =arr[i] Γ left[i] Γ right[i].This gives the sum of
arr[i]across all subarrays where it's the minimum.
Sum All Contributions:
Add up all individual contributions to get the final result.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the size of the array. Each element is pushed and popped from the stack at most once, resulting in linear time complexity.
Expected Auxiliary Space Complexity: O(n), as we use additional arrays for left and right boundaries and a stack for processing, all of which require O(n) space.
π§βπ» Code (C++)
π§βπ» Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated