795. Number of Subarrays with Bounded Maximum

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] .
  1. 思路
  • 遇到一个值A[i]时,进行判断,若L<= A[i] && A[i] <= R,说明A [j : i] 是符合题目要求的子串,记录下 i - j + 1:res += i - j + 1, count = i - j + 1。
  • 若 L > A[i] ,说明A [j : i] 是符合题目要求的子串,但是其中只有count记录的长度在L~R范围内,其余部分小于L,只需res += count即可。
  • 如果 A[i] > R,继续。

java

class Solution {
    public int numSubarrayBoundedMax(int[] A, int L, int R) {
        int res = 0, count = 0, j = 0;
        for (int i = 0; i < A.length; i++ ) {
            if (  L <= A[i] && A[i] <= R) {
                res += i - j + 1;
                count = i - j + 1;
            }
            else if (A[i] < L) {
                res += count;
            }
            else {
                j = i + 1;
                count = 0;
            }
        }
        return res;
    } 
    }

python

class Solution:
    def numSubarrayBoundedMax(self, A: List[int], L: int, R: int) -> int:
        res = 0
        count = 0
        j = 0
        for i in range(len(A)):
            if A[i] <= R and A[i] >= L:
                res += i - j + 1
                count = i - j +  1
            elif A[i] < L:
                res += count
            else:
                j = i + 1
                count = 0
        return res
                
                
        

Python

class Solution:
    def numSubarrayBoundedMax(self, A: List[int], L: int, R: int) -> int:
        a, b, result = -1, -1, 0
        for i in range(len(A)):
            if A[i] < L:
                if a == -1:
                    a = i
                elif b != -1:
                    result += b - a + 1
            elif A[i] > R:
                a, b = -1, -1
            else:
                if a == -1:
                    a = i
                b=i
                result += b - a + 1
        return result