Leetcode 907: Sum of Subarray Minimums

grid47
grid47
Exploring patterns and algorithms
Aug 8, 2024 7 min read

Given an array of integers arr, find the sum of the minimum values of all contiguous subarrays of arr. Since the result can be very large, return it modulo 10^9 + 7.
Problem
Approach
Steps
Complexity
Input: An array of integers `arr` representing the input.
Example: Input: arr = [5, 3, 8, 6]
Constraints:
• 1 <= arr.length <= 30,000
• 1 <= arr[i] <= 30,000
Output: An integer representing the sum of the minimum values of all subarrays, modulo 10^9 + 7.
Example: Output: 35
Constraints:
Goal: Compute the sum of the minimum elements for all contiguous subarrays efficiently.
Steps:
• Use a monotonic stack to calculate the contribution of each element as the minimum in its range.
• Track the range on the left and right where the current element is the minimum.
• Multiply the contribution of each element by its value and sum all contributions.
Goal: Limitations for the input and expected result.
Steps:
• The input array can contain up to 30,000 elements.
• All values in the array are positive integers.
Assumptions:
• The array contains at least one element.
• All elements in the array are non-negative integers.
Input: Input: arr = [5, 3, 8, 6]
Explanation: Subarrays are [5], [3], [8], [6], [5, 3], [3, 8], [8, 6], [5, 3, 8], [3, 8, 6], [5, 3, 8, 6]. Minimums are 5, 3, 8, 6, 3, 3, 6, 3, 3, 3. Sum is 35.

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

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus