#795
Number of Subarrays with Bounded Maximum
MediumApproaches
💡
Intuition
Time O(n²)Space O(1)
The brute force approach involves checking every possible subarray and determining if its maximum falls within the specified range. This is straightforward but inefficient for larger arrays.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a count variable to zero.
- 2Step 2: Use two nested loops to generate all possible subarrays.
- 3Step 3: For each subarray, find the maximum element and check if it lies within the range [left, right]. If it does, increment the count.
solution.py14 lines
1# Full working Python code
2
3def numSubarrayBoundedMax(nums, left, right):
4 count = 0
5 n = len(nums)
6 for i in range(n):
7 max_val = nums[i]
8 for j in range(i, n):
9 max_val = max(max_val, nums[j])
10 if left <= max_val <= right:
11 count += 1
12 if max_val > right:
13 break
14 return countℹ
Complexity note: The time complexity is O(n²) because we are generating all subarrays using two nested loops, leading to a quadratic number of checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.