![]() |
VOOZH | about |
Given an integer array arr[] and two integers l and r. The task is to find the count of subarrays where the maximum element in that subarray is in range [l, r]. In other words, the max element is at least l and at most r.
Examples:
Input: arr[] = [1, 2, 3, 4, 5], l = 2, r = 5
Output: 11
Explanation: Valid subarrays are: [2], [3], [4], [5], [1,2], [2,3], [3,4], [4,5], [1,2,3], [2,3,4], [3,4,5], [1,2,3,4], [2,3,4,5], [1,2,3,4,5].Input: arr[] = [3, 1, 6, 4], l = 3, r = 6
Output: 9
Explanation: Valid subarrays are: [3], [6], [4], [3,1], [1,6], [6,4], [3,1,6], [1,6,4], [3,1,6,4].Input: arr[] = [1, 2, 3, 4], l = 5, r = 7
Output: 0
Explanation: There is no subarray where the maximum element is at least 5 and at most 7.
Table of Content
The idea is to generate all subarrays and determine the maximum element in each. By iterating over all starting and ending indices, we keep track of the max value and check if it falls within the range [l, r].
14
The idea is to efficiently count subarrays where the maximum element falls within the given range. Instead of checking all subarrays, we use a two-pointer approach to track valid subarrays in a single pass. When encountering an element greater than the upper bound, we reset our tracking, while elements within range help extend valid subarrays. This eliminates redundant checks, optimizing the process to linear time complexity.
Steps to implement the above idea:
14