Problem Description
Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the maximum element in each subarray is between left and right (inclusive).
Key Insights
- The problem asks for subarrays where the maximum element is within [left, right].
- Instead of directly counting valid subarrays, we can count subarrays with maximum ≤ right and subtract those with maximum < left.
- Use a sliding window (or two pointers) approach to efficiently count subarrays in a single pass over the array.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the array, because we iterate over the array a constant number of times. Space Complexity: O(1), as we use a fixed number of extra variables.
Solution
We solve the problem by defining a helper function that counts the number of contiguous subarrays where all elements are less than or equal to a given bound. The number of valid subarrays is equal to:
count_subarrays(right) - count_subarrays(left - 1)
The helper function iterates through the array, and for each element that is less than or equal to the bound, it increments a running count (currentCount). If an element exceeds the bound, the running count resets to zero since it cannot be part of a valid subarray for this count. Adding the currentCount to a global counter gives the total valid subarrays under the current bound.
This approach efficiently manages segments of valid numbers and computes the difference to result in the answer.