Leetcode 795. Number of Subarrays with Bounded Maximum
Given an integer array nums
and two integers left
and right
, return the number of contiguous subarrays where the value of the maximum array element is in the range [left, right]
.
nums
?nums
array?left
and right
inclusive?#include <vector>
class Solution {
public:
int numSubarrayBoundedMax(std::vector<int>& nums, int left, int right) {
return countSubarrays(nums, right) - countSubarrays(nums, left - 1);
}
private:
int countSubarrays(std::vector<int>& nums, int bound) {
int count = 0, current = 0;
for (int num : nums) {
if (num <= bound) {
current++;
} else {
current = 0;
}
count += current;
}
return count;
}
};
To solve this problem effectively, we can break it down into simpler parts:
countSubarrays
that counts the number of subarrays where the maximum element is less than or equal to a given bound.right
bound and then subtract the count of subarrays up to left - 1
.[left, right]
range by exclusion.The time complexity of this solution is O(n)
, where n
is the length of the nums
array. This is because we only iterate through the array a limited number of times (specifically, twice) to gather the required counts. Each element is processed in constant time during each iteration, making this approach efficient for large input sizes.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?