[leetcode] 907. Sum of Subarray Minimums

Description

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. 1 <= A.length <= 30000
  2. 1 <= A[i] <= 30000

分析

题目的意思是:求一个序列的所有连续子序列的最小值的和,这道题用暴力破解的方法肯定会超时,存在着大量的重复的操作。我尝试找规律,发现没有找到,看了答案以后,才发现原来可以把问题看成一个i长度为结尾序列的求解,i从1扩大到n就是所求了。
对于

A = [1,7,5,2,4,3,9]

[i,j]的子序列的最小值为:B = [1,2,2,2,3,3,9],
即i=0的时候是整个数列 [1,7,5,2,4,3,9] 最小值为1,当i=1的时候,序列为[7,5,2,4,3,9],最小值为2,依次类推就行了,这个规律我没有想到,欣赏一下,理解了这个过程就可以看代码了,代码用的是栈来实现的

代码

class Solution:
    def sumSubarrayMins(self, A: List[int]) -> int:
        MOD=10**9+7
        stack=[]
        ans=dot=0
        for j,y in enumerate(A):
            cnt=1
            while stack and stack[-1][0]>=y:
                x,c=stack.pop()
                cnt+=c
                dot-=x*c
            stack.append([y,cnt])
            dot+=y*cnt
            ans+=dot
        return ans% MOD
        

参考文献

[LeetCode] Approach 2: Maintain Stack of Minimums

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值