Total of Every Subarray's Minimum Value

Implement sumSubarrayMinimums

Given an integer array arr, find the sum of the minimum values of every contiguous subarray. Enumerating every subarray directly works but wastes effort — a smarter approach flips the question: instead of "what's the minimum of this subarray?", ask "in how many subarrays is this element the minimum?" for each element individually. An element is the minimum of exactly the subarrays that start somewhere between its nearest strictly-smaller neighbor to the left and itself, and end somewhere between itself and its nearest smaller-or-equal neighbor to the right — both boundaries found in a single monotonic-stack pass each. Multiplying each element's value by how many such subarrays it dominates, and summing across every element, reaches the same total in O(n) instead of O(n²).

Example 1:

Input: arr = [5,2,6,1,4]

Output: 31

Example 2:

Input: arr = [6,3,8,2]

Output: 34

Example 3:

Input: arr = [9,5,7,1,4]

Output: 48

+ 3 hidden test cases run on Submit.

Constraints:

  • 1 ≤ arr.length ≤ 12
  • 1 ≤ arr[i] ≤ 100
  • The answer fits comfortably in a 32-bit signed integer for this input size

arr =

[5, 2, 6, 1, 4]