题目
解法1:O(n*n),暴力
class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
n = len(arr)
ans = 0
for i in range(n):
curr_min = arr[i]
for j in range(i,n):
curr_min = min(curr_min,arr[j])
ans += curr_min
ans %= 10**9+7
return ans
解法2: O(n),单调栈
参考:https://leetcode.com/problems/sum-of-subarray-minimums/discuss/178876/stack-solution-with-very-detailed-explanation-step-by-step
- 维持一个单调递增栈
- 单调递增栈的作用在于,对于当前元素,可以快速知道在前面部分比这个元素小的元素在哪,同时知道在后面部分比这个元素小的元素在哪
- 对于这个题目来说,在找到的这个所有边界内,形成的任意subarray只要包括当前元素,那这个subarray的最小元素就是当前元素
- 这道题在implement的时候,处理第一个元素和最后一个元素需要做一点处理
class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
n = len(arr)
min_stack = []
ans = 0
for i in range(n+1):
# keep a monotonous increasing stack (which records the index)
# for the curr number, we know the most close number from the left which is smaller than curr num is just the one in the stack before curr
# likewise, we know the number at i is the most close number from right because of the constrain in while loop
# in that case we found the range (left,curr] and [curr,right) where curr will be the minimum number in any of the array in between
# and we are free to pick any number of elements from the left and right with the current number to form a subarray where the minimum
# number if the curr number
while min_stack and arr[min_stack[-1]] > (arr[i] if i < n else -float('inf')):
curr = min_stack.pop()
left_less = min_stack[-1] if min_stack else -1
ans += arr[curr] * (curr-left_less) * (i-curr)
ans %= 10**9+7
# print(min_stack,arr[curr],curr-left_less,i-curr)
min_stack.append(i)
return ans