Number of Subarrays with Bounded Maximum


In this solution, we define a helper function count
which counts the number of subarrays where the maximum element is less than or equal to its argument.
We then use this helper function to count the number of subarrays with maximum element less than or equal to right
and subtract the count of subarrays with maximum element less than left  1
.
The result of this subtraction is the count of subarrays where the maximum element is in the range [left, right]
, which is the desired output.
This algorithm works because every subarray of the array nums
is included exactly once in either count(right)
or count(left  1)
. Thus, subtracting these two counts gives the correct answer.