Stacks and Queues Monotonic stack
216. Sum of Subarray Minimums
You are given an array of non-negative integers nums. Every subarray has a minimum, its smallest
element. Return the sum of the minimums of all the subarrays of nums.
A subarray is a contiguous run of one or more elements. Two subarrays are different if they start or end at different positions, even when they hold the same values. A subarray whose smallest value appears more than once still adds that value only once.
The total can be very large, so return it modulo 109 + 7, which means the remainder after dividing it by 1,000,000,007.
Example 1
Input: nums = [6, 2, 5, 4]
31Explanation: The four single elements give 6 + 2 + 5 + 4 = 17. Every longer subarray holds the 2 and has minimum 2,
except [5,4], whose minimum is 4. That adds 5 × 2 + 4 = 14, so the total is 31.
Example 2
Input: nums = [5, 5, 5]
30Explanation: There are six subarrays, three of length 1, two of length 2 and one of length 3. Each has minimum 5, so the total is 6 × 5 = 30.
Example 3
Input: nums = [1000000000, 0, 1000000000]
999999993Explanation: Only the two single 109s have a minimum above 0, so the exact total is 2,000,000,000. Its remainder after dividing by 1,000,000,007 is 999,999,993.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 1050 ≤ nums[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.