LeetCode Solutions
795. Number of Subarrays with Bounded Maximum
Time: $O(n)$ Space: $O(1)$
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;
}
};
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;
}
}
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