795. Number of Subarrays with Bounded Maximum

87 篇文章 0 订阅

 

We are given an array A of positive integers, and two positive integers L and R (L <= R).

Return the number of (contiguous, non-empty) subarrays such that the value of the maximum array element in that subarray is at least L and at most R.

Example :
Input: 
A = [2, 1, 4, 3]
L = 2
R = 3
Output: 3
Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].

Note:

  • L, R  and A[i] will be an integer in the range [0, 10^9].
  • The length of A will be in the range of [1, 50000].

 

注意处理遗漏的情况,比如L=2, R=4, A=[1,1,1,3]

 

dp[0]=0, dp[1]=0, dp[2]=0, dp[3]!=dp[2]+1

dp[3]而是=4

class Solution:
    def numSubarrayBoundedMax(self, A, L, R):
        """
        :type A: List[int]
        :type L: int
        :type R: int
        :rtype: int
        """
        if not A: return 0
        dp = [0 for _ in range(len(A))]
        dp[0] = 1 if L<=A[0]<=R else 0
        
        for i in range(1, len(A)):
            if A[i]>R: continue
            if A[i]<L: dp[i]=dp[i-1]
            else: 
                j = i-1
                # 处理遗漏的情况
                while j>=0 and A[j]<L: j-=1
                dp[i]=dp[i-1]+i-j
        return sum(dp)
    
s=Solution()
print(s.numSubarrayBoundedMax([2,1,4,3], 2, 3))
print(s.numSubarrayBoundedMax([73,55,36,5,55,14,9,7,72,52], 32, 69))

写上面的解法得到的启发

class Solution:
    def numSubarrayBoundedMax(self, A, L, R):
        """
        :type A: List[int]
        :type L: int
        :type R: int
        :rtype: int
        """
        res=cnt=prev=0
        for i in range(len(A)):
            if L<=A[i]<=R: 
                res+=i-prev+1  # 以i结尾的情况
                cnt=i-prev+1  # 多大范围没有比L小或者比R大的
            elif A[i]<L:
                res+=cnt      # 必须要依赖前面一个的
            else:
                prev=i+1
                cnt=0
        return res
        
class Solution:
    def numSubarrayBoundedMax(self, A, L, R):
        """
        :type A: List[int]
        :type L: int
        :type R: int
        :rtype: int
        """
        res=start=prev=0
        for i,v in enumerate(A):
            if L<=v<=R:
                t=i-start+1    # 以当前位置为结果OK的个数
                res+=t
                prev=t
            elif v<L:
                res+=prev      # 必须以前一个位置结束
            else:
                start=i+1      # 没有大于R的index开始位置
                prev=0
        return res
        

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值