LWC 74: 795. Number of Subarrays with Bounded Maximum

Posted Demon的黑与白

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LWC 74: 795. Number of Subarrays with Bounded Maximum相关的知识,希望对你有一定的参考价值。

LWC 74: 795. Number of Subarrays with Bounded Maximum

传送门:795. Number of Subarrays with Bounded Maximum

Problem:

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和R之间的最大值val符合 val in [L, R], 可以转为:求区间内的任意值x , x in [L, R]。所以,把数组的每个位置当作起点,如A = [2, 1, 4, 3]:

位置0: [2], [2, 1], [2, 1, 4], [2, 1, 4, 3]
位置1: [1], [1, 4], [1, 4, 3]
位置2: [4], [4, 3]
位置3: [3]

for each subset in each position:
calculate whether the last value in subset <= R

你会发现,考虑位置0,subset[2, 1, 4]中的last value 4时,因为4 > R,所以删除该subset,且连同位置123中包含4的子集可以一并删除。

代码如下:

    public int numSubarrayBoundedMax(int[] A, int L, int R) 
        return count(A, R) -count(A, L - 1);
    

    int count(int[] a, int r) 
        int ret = 0;
        int cnt = 0;
        for (int v : a) 
            if (v <= r) cnt ++;
            else cnt = 0;
            ret += cnt;
        
        return ret;
    

Python版本:

class Solution(object):
    def numSubarrayBoundedMax(self, A, L, R):
        """
        :type A: List[int]
        :type L: int
        :type R: int
        :rtype: int
        """
        def count(A, R):
            ret = cnt = 0
            for v in A:
                cnt = cnt + 1 if v <= R else 0
                ret += cnt
            return ret

        return count(A, R) - count(A, L - 1)

以上是关于LWC 74: 795. Number of Subarrays with Bounded Maximum的主要内容,如果未能解决你的问题,请参考以下文章

LWC 74: 792. Number of Matching Subsequences

LWC 74: 792. Number of Matching Subsequences

LWC 74: 793. Preimage Size of Factorial Zeroes Function

LWC 74: 793. Preimage Size of Factorial Zeroes Function

LWC 109: 933.Number of Recent Calls

LWC 109: 933.Number of Recent Calls