Given an integer array nums and two integers left and right, return _the number of contiguous non-emptysubarrays such that the value of the maximum array element in that subarray is in the range _[left, right].
The test cases are generated so that the answer will fit in a 32-bit integer.
The number of subarrays where the max is in [left, right] = (number of subarrays where max ≤ right) - (number of subarrays where max < left). We can count subarrays with max ≤ bound using a two-pointer approach.
classSolution {
public:int numSubarrayBoundedMax(vector<int>& nums, int left, int right) {
returncount(nums, right) - count(nums, left-1);
}
intcount(vector<int>& nums, int bound) {
int ans =0, cur =0;
for (int x : nums) {
if (x <= bound) cur++;
else cur =0;
ans += cur;
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
funcnumSubarrayBoundedMax(nums []int, left, rightint) int {
returncount(nums, right) -count(nums, left-1)
}
funccount(nums []int, boundint) int {
ans, cur:=0, 0for_, x:=rangenums {
ifx<=bound {
cur++ } else {
cur = 0 }
ans+=cur }
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
publicintnumSubarrayBoundedMax(int[] nums, int left, int right) {
return count(nums, right) - count(nums, left-1);
}
privateintcount(int[] nums, int bound) {
int ans = 0, cur = 0;
for (int x : nums) {
if (x <= bound) cur++;
else cur = 0;
ans += cur;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funnumSubarrayBoundedMax(nums: IntArray, left: Int, right: Int): Int {
funcount(bound: Int): Int {
var ans = 0var cur = 0for (x in nums) {
if (x <= bound) cur++else cur = 0 ans += cur
}
return ans
}
return count(right) - count(left-1)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defnumSubarrayBoundedMax(self, nums: list[int], left: int, right: int) -> int:
defcount(bound):
ans = cur =0for x in nums:
if x <= bound:
cur +=1else:
cur =0 ans += cur
return ans
return count(right) - count(left-1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfnnum_subarray_bounded_max(nums: Vec<i32>, left: i32, right: i32) -> i32 {
fncount(nums: &Vec<i32>, bound: i32) -> i32 {
letmut ans =0;
letmut cur =0;
for&x in nums {
if x <= bound {
cur +=1;
} else {
cur =0;
}
ans += cur;
}
ans
}
count(&nums, right) - count(&nums, left-1)
}
}