 All Problems
Sum of Subarray Minimums
medium
stack
arrays
monotonic stack
amazon
google
facebook

Given an array of integers arr, find the sum of min(b) for every subarray b of arr. Return the answer modulo 10⁹ + 7.

Example 1:

Input: 3 1 2 4
Output: 17
Explanation: Subarrays: [3]=3, [1]=1, [2]=2, [4]=4, [3,1]=1, [1,2]=1, [2,4]=2, [3,1,2]=1, [1,2,4]=1, [3,1,2,4]=1. Sum = 17.

Example 2:

Input: 11 81 94 43 3
Output: 444

Constraints:

  • 1 ≤ arr.length ≤ 3 × 10⁴
  • 1 ≤ arr[i] ≤ 3 × 10⁴

Input format: One line — space-separated integers.

Output format: Sum mod 10⁹+7.

Run to check your code against the sample cases, or submit to run every case