907. Sum of Subarray Minimums
https://leetcode.com/problems/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 109 + 7
.
Example 1:
Example 2:
Constraints:
1 <= arr.length <= 3 * 104
1 <= arr[i] <= 3 * 104
问数组的所有子数组内最小值的和。sum(arr(i) * cnt(i)), cnt(i) 是以arr[i]为最小值的子数组个数。设[l, i, r]是以arr[i]为最小值的最长子数组,那cnt[i]即(左边选个长度 * 右边选个长度)的所有可能性: (i - l) * (r - i). 为了对每个arr[i]找到对应的l和r,用monotonic stack存当前最小值所在index,当arr[i]比s[-1]还小时,抛出s[-1]且res += (i - s[-1]) * (s[-1] * s[-2]), 在s.append(i)。
Last updated
Was this helpful?