907. Sum of Subarray Minimums

题目

在这里插入图片描述

解法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
                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值