Sum of Subarray Minimums

Given an array of integers `arr`, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer modulo `10^9 + 7`.

30:00

Sum of Subarray Minimums
medium
Free written solution
Topics
Companies

Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 10^9 + 7.

Example 1:
Input: {"arr":[3,1,2,4]}
Output: 17
Constraints:
  • 1≤arr.length≤3×1041 \leq \text{arr.length} \leq 3 \times 10^4

  • 1≤arr[i]≤3×1041 \leq \text{arr}[i] \leq 3 \times 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"arr":[3,1,2,4]}
i –
cur –
stack depth 0
total 0

3

0

1

1

2

2

4

3

on stack

current

popped: the minimum

smaller walls

stack (bottom → top, values rise)

empty

Each value is the minimum of a run of subarrays. Keep a stack of indexes whose values rise from bottom to top, and count a value's subarrays when it gets popped.

Variables
VariableValue
stack[]
total0
DepthFunction Call
Stack empty
0/16