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>& nums, int left, int right) {
    int ans = 0;
    int l = -1;
    int r = -1;

    for (int i = 0; i < nums.size(); ++i) {
      if (nums[i] > right)  // Handle the reset value.
        l = i;
      if (nums[i] >= left)  // Handle the reset and the 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[] nums, int left, int right) {
    int ans = 0;
    int l = -1;
    int r = -1;

    for (int i = 0; i < nums.length; ++i) {
      if (nums[i] > right) // Handle the reset value.
        l = i;
      if (nums[i] >= left) // Handle the reset and the 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, nums: List[int], left: int, right: int) -> int:
    ans = 0
    l = -1
    r = -1

    for i, num in enumerate(nums):
      if num > right:  # Handle the reset value.
        l = i
      if num >= left:  # Handle the reset and the needed value.
        r = i
      ans += r - l

    return ans