Intermediate Level
Implement the boundedMaximumSubarrayCount method that counts subarrays whose maximum value stays within a given range.
You are given an integer array and two boundary values left and right. Count how many continuous subarrays have a maximum element between left and right, inclusive.
A subarray is invalid if all its values are smaller than left, or if any value is greater than right.
Scan the array and keep track of two positions: the last index where a value was greater than right, and the last index where a value was at least left.
For each index, any subarray ending there must start after the last too-large value. It is valid only if it includes at least one value inside the range. The number of valid subarrays ending at the current index is lastInRange - lastTooLarge.
Add this count for every index.
Pseudocode:
function boundedMaximumSubarrayCount(nums, size, left, right):
lastTooLarge = -1
lastInRange = -1
answer = 0
for i from 0 to size - 1:
if nums[i] > right:
lastTooLarge = i
if nums[i] >= left and nums[i] <= right:
lastInRange = i
if lastInRange > lastTooLarge:
answer += lastInRange - lastTooLarge
return answer