Skip to content

795. Number of Subarrays with Bounded Maximum 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
    int ans = 0;
    int l = -1;
    int r = -1;

    for (int i = 0; i < A.size(); ++i) {
      if (A[i] > R)  // Handle reset value
        l = i;
      if (A[i] >= L)  // Handle reset and needed value
        r = i;
      ans += r - l;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int numSubarrayBoundedMax(int[] A, int L, int R) {
    int ans = 0;
    int l = -1;
    int r = -1;

    for (int i = 0; i < A.length; ++i) {
      if (A[i] > R) // Handle reset value
        l = i;
      if (A[i] >= L) // Handle reset and needed value
        r = i;
      ans += r - l;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def numSubarrayBoundedMax(self, A: List[int], L: int, R: int) -> int:
    ans = 0
    l = -1
    r = -1

    for i, a in enumerate(A):
      if a > R:
        l = i
      if a >= L:
        r = i
      ans += r - l

    return ans