907. 子数组的最小值之和

碰到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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值