You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray.
Return the sum of all subarray ranges of nums.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,2,3]
Output: 4
Explanation: The 6 subarrays of nums are the following:
[1], range = largest - smallest = 1 - 1 = 0
[2], range = 2 - 2 = 0
[3], range = 3 - 3 = 0
[1,2], range = 2 - 1 = 1
[2,3], range = 3 - 2 = 1
[1,2,3], range = 3 - 1 = 2
So the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4.
Example 2:
Input: nums = [1,3,3]
Output: 4
Explanation: The 6 subarrays of nums are the following:
[1], range = largest - smallest = 1 - 1 = 0
[3], range = 3 - 3 = 0
[3], range = 3 - 3 = 0
[1,3], range = 3 - 1 = 2
[3,3], range = 3 - 3 = 0
[1,3,3], range = 3 - 1 = 2
So the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4.
Example 3:
Input: nums = [4,-2,-3,4,1]
Output: 59
Explanation: The sum of all subarray ranges of nums is 59.
Constraints:
1 <= nums.length <= 1000
-109 <= nums[i] <= 109
问数组的所有子数组内(最大值-最小值)的和。相当于求所有子数组内最大值的和-所有子数组内最小值的和。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)。
class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
A, s, res = [-inf] + nums + [-inf], [], 0
for i, num in enumerate(A):
while s and num < A[s[-1]]:
j = s.pop()
res -= (i - j) * (j - s[-1]) * A[j]
s.append(i)
A, s = [inf] + nums + [inf], []
for i, num in enumerate(A):
while s and num > A[s[-1]]:
j = s.pop()
res += (i - j) * (j - s[-1]) * A[j]
s.append(i)
return res pytho