Number of Subarrays with Bounded Maximum - Problem
Given an integer array nums and two integers left and right, we need to find the number of contiguous non-empty subarrays where the maximum element falls within the range [left, right] (inclusive).
Think of this as finding all possible "windows" in the array where the largest number in that window is neither too small (less than left) nor too large (greater than right).
Example: If we have array [2, 1, 4, 9, 3] with left = 2 and right = 4, we count subarrays like [2], [2, 1], [4], [3], etc., but not [9] or [4, 9] since 9 is too large.
The challenge is to do this efficiently without checking every possible subarray individually!
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [2,1,4,9,3], left = 2, right = 4
โบ
Output:
3
๐ก Note:
Valid subarrays are [2], [4], [3]. Subarrays like [2,1] have max=2 (valid), [1,4] has max=4 (valid), [4,9] has max=9 (invalid), etc. Total count is 3.
example_2.py โ All Elements in Range
$
Input:
nums = [2,9,2,5,6], left = 2, right = 8
โบ
Output:
7
๐ก Note:
Elements 2,2,5,6 are in range [2,8], only 9 is out of range. Valid subarrays: [2],[2],[5],[6],[2,2],[2,5],[5,6] = 7 subarrays.
example_3.py โ Single Element
$
Input:
nums = [1], left = 1, right = 1
โบ
Output:
1
๐ก Note:
Only one subarray [1] exists, and its maximum (1) is within range [1,1], so answer is 1.
Constraints
- 1 โค nums.length โค 105
- 0 โค nums[i] โค 109
- 0 โค left โค right โค 109
- The answer is guaranteed to fit in a 32-bit integer
Visualization
Tap to expand
Understanding the Visualization
1
Count groups with quality โค upper limit
Walk the conveyor belt and count all consecutive groups where no product exceeds the upper quality limit
2
Count groups with quality โค (lower limit - 1)
Do the same counting but with a threshold one less than our lower quality limit
3
Subtract to get perfect range
The difference gives us exactly the groups with quality in our target range
Key Takeaway
๐ฏ Key Insight: Instead of checking O(nยฒ) subarrays individually, we count valid subarrays mathematically using subtraction: count(max โค right) - count(max โค left-1) = count(max โ [left,right])
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code