795. 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 < = n u m s . l e n g t h < = 1 0 5 1 <= nums.length <= 10^5 1<=nums.length<=105
- 0 < = n u m s [ i ] < = 1 0 9 0 <= nums[i] <= 10^9 0<=nums[i]<=109
- 0 < = l e f t < = r i g h t < = 1 0 9 0 <= left <= right <= 10^9 0<=left<=right<=109
From: LeetCode
Link: 795. Number of Subarrays with Bounded Maximum
Solution:
Ideas:
-
start tracks the last index where nums[i] > right, which invalidates any subarray containing it.
-
prevCount holds the number of valid subarrays ending at the previous index — it’s used to accumulate results.
-
The idea is:
- When nums[i] is within [left, right], all subarrays ending at i and starting after start are valid.
- When nums[i] < left, we can reuse previous valid subarrays.
- When nums[i] > right, we reset since any subarray containing it is invalid.
Code:
int numSubarrayBoundedMax(int* nums, int numsSize, int left, int right) {
int count = 0;
int prevCount = 0; // Number of valid subarrays ending at previous index
int start = -1; // Start of the most recent segment where nums[i] > right
for (int i = 0; i < numsSize; i++) {
if (nums[i] >= left && nums[i] <= right) {
// Current number is within bounds: extend all subarrays after 'start'
prevCount = i - start;
count += prevCount;
} else if (nums[i] < left) {
// Can only be added to subarrays that already have a valid max
count += prevCount;
} else {
// nums[i] > right: break the valid segment
start = i;
prevCount = 0;
}
}
return count;
}