oneby7

Stacks and Queues Monotonic stack

216. Sum of Subarray Minimums

Medium

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]

Output: 31

Explanation: 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]

Output: 30

Explanation: 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]

Output: 999999993

Explanation: 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.

nums = [2, 1, 2]

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.