classSolution:defsumSubarrayMins(self,arr: List[int]) ->int: n =len(arr) left = [-1] * n right = [n] * n stack = []for i, value inenumerate(arr):while stack and arr[stack[-1]]>= value: stack.pop()if stack: left[i]= stack[-1] stack.append(i) stack = [] for i inrange(n -1, -1, -1):while stack and arr[stack[-1]]> arr[i]: stack.pop()if stack: right[i]= stack[-1] stack.append(i) mod =10**9+7 result =sum((i - left[i]) * (right[i] - i) * value for i, value inenumerate(arr))% mod return result
时间复杂度:O()
空间复杂度:O()
暴力解法超时
classSolution:defsumSubarrayMins(self,arr: List[int]) ->int: res_list = []for i inrange(len(arr)):for j inrange(i+1, len(arr)+1):# 注意边界 res_list.append(min(arr[i:j])) mod =10**9+7returnsum(res_list)% mod