classSolution: defsumSubarrayMins(self, arr: List[int]) -> int: mod = 10 ** 9 + 7 result = 0 n = len(arr) left = [0] * n right = [0] * n a_stack = [] for i inrange(n): # 从左往右遍历,找以arr[i]为最右且最小的子数组的数量 while a_stack and arr[a_stack[-1]] >= arr[i]: a_stack.pop() left[i] = i - (a_stack[-1] if a_stack else -1) a_stack.append(i) a_stack = [] for i inrange(n - 1, -1, -1): # 从右往左遍历,找以arr[i]为最左且最小的子数组的数量 while a_stack and arr[a_stack[-1]] > arr[i]: a_stack.pop() right[i] = (a_stack[-1] if a_stack else n) - i a_stack.append(i) for num, l, r inzip(arr, left, right): # 计算结果 result = (result + num * l * r) % mod return result
classSolution: defsubArrayRanges(self, nums: List[int]) -> int: n = len(nums) max_sum = 0 min_sum = 0 left = [-1] * n right = [n] * n a_stack = [] for i inrange(n): # 先求最大 while a_stack and nums[a_stack[-1]] <= nums[i]: right[a_stack.pop()] = i if a_stack: left[i] = a_stack[-1] a_stack.append(i) for i, (num, l, r) inenumerate(zip(nums, left, right)): max_sum += num * (i - l) * (r - i) left = [-1] * n right = [n] * n a_stack = [] for i inrange(n): # 再求最小 while a_stack and nums[a_stack[-1]] >= nums[i]: right[a_stack.pop()] = i if a_stack: left[i] = a_stack[-1] a_stack.append(i) for i, (num, l, r) inenumerate(zip(nums, left, right)): min_sum += num * (i - l) * (r - i) return max_sum - min_sum