Given an array of integers A, find the sum of min(B), where B ranges over every (contiguous) subarray of A.
Since the answer may be large, return the answer modulo 10^9 + 7.
Example 1:
Input: [3,1,2,4]
Output: 17
Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17.
Note:
1 <= A.length <= 30000
1 <= A[i] <= 30000
分析:假设数组为a,对于index为i的数,假设其连续左边直到m的数都比他大或者相等,连续右边n个数都比他大,那以a[i]为最小值的子列的个数一共有m*n个,那其实对于数组中的每个数,我们只要计算出其对应的m和n就ok, m和n可以用一个单调栈就可以很容易实现。
class Solution(object):
def sumSubarrayMins(self, A):
"""
:type A: List[int]
:rtype: int
"""
if(len(A)==1):
return A[0]
left = [0 for i in range(len(A))]
right = [0 for i in range(len(A))]
left[0] = 1
stack = []
stack.append(0)
for i in range(1, len(A)):
while len(stack)>0 and A[i]<=A[stack[len(stack)-1]]:
stack.pop()
if len(stack)==0:
left[i] = i+1
else:
left[i] = i-stack[len(stack)-1]
stack.append(i)
stack=[]
stack.append(len(A)-1)
right[len(A)-1] = 1
for i in range(len(A)-2, -1, -1):
while len(stack)>0 and A[i]<A[stack[len(stack)-1]]:
stack.pop()
if len(stack)==0:
right[i] = len(A)-i
else:
right[i] = stack[len(stack)-1]-i
stack.append(i)
res = 0
for i in range(len(A)):
res = (res + A[i]*left[i]*right[i])%(int(1e9+7))
return res