795. Number of Subarrays with Bounded Maximum LeetCode Solution
In this guide, you will get 795. Number of Subarrays with Bounded Maximum LeetCode Solution with the best time and space complexity. The solution to Number of Subarrays with Bounded Maximum problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Number of Subarrays with Bounded Maximum solution in C++
- Number of Subarrays with Bounded Maximum solution in Java
- Number of Subarrays with Bounded Maximum solution in Python
- Additional Resources

Problem Statement of Number of Subarrays with Bounded Maximum
Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays 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.
Example 1:
Input: nums = [2,1,4,3], left = 2, right = 3
Output: 3
Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].
Example 2:
Input: nums = [2,9,2,5,6], left = 2, right = 8
Output: 7
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 109
0 <= left <= right <= 109
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
795. Number of Subarrays with Bounded Maximum LeetCode Solution in C++
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;
}
};
/* code provided by PROGIEZ */
795. Number of Subarrays with Bounded Maximum LeetCode Solution in Java
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;
}
}
// code provided by PROGIEZ
795. Number of Subarrays with Bounded Maximum LeetCode Solution in Python
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
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.