碰到leetcode907,子数组的最小值之和,用python3按自己思路写死都过不去,怎么都超时,这是python3代码:
class Solution:
def sumSubarrayMins(self, A):
"""
:type A: List[int]
:rtype: int
"""
res = 0
length = len(A)
for i in range(length):
left = 0
right = 0
if i > 0:
j = i - 1
while j >= 0 and A[j] > A[i]:
left += 1
j -= 1
if i < length - 1:
k = i + 1
while k < length and A[k] >= A[i]:
k += 1
right += 1
res += A[i] * (left * right + (left + right + 1))
return res % (10**9 + 7)
按这思路,cpp写提交勉强通过,时间和内存让人哭笑不得
超过了0.9%的用户。。。。。。。
跑去leetcode原网站找了两个python解法代码,真的厉害了:
可代码思路没咋明白,先做马来人,日后再见!
220ms代码:
class Solution:
def sumSubarrayMins(self, A):
"""
:type A: List[int]
:rtype: int
"""
MOD = 10**9 + 7
stack = []
ans = dot = 0
for j, y in enumerate(A):
# Add all answers for subarrays [i, j], i <= j
count = 1
while stack and stack[-1][0] >= y:
x, c = stack.pop()
count += c
dot -= x * c
stack.append((y, count))
dot += y * count
ans += dot
return ans % MOD
440ms代码:
class Solution:
def sumSubarrayMins(self, A):
"""
:type A: List[int]
:rtype: int
"""
MOD = 10**9 + 7
N = len(A)
# prev has i* - 1 in increasing order of A[i* - 1]
# where i* is the answer to query j
stack = []
prev = [None] * N
for i in range(N):
while stack and A[i] <= A[stack[-1]]:
stack.pop()
prev[i] = stack[-1] if stack else -1
stack.append(i)
# next has k* + 1 in increasing order of A[k* + 1]
# where k* is the answer to query j
stack = []
next_ = [None] * N
for k in range(N-1, -1, -1):
while stack and A[k] < A[stack[-1]]:
stack.pop()
next_[k] = stack[-1] if stack else N
stack.append(k)
# Use prev/next array to count answer
return sum((i - prev[i]) * (next_[i] - i) * A[i]
for i in range(N)) % MOD
这是代码原址:https://leetcode.com/problems/sum-of-subarray-minimums/solution/