VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-subarrays-maximum-value-given-range/

⇱ Count subarrays with max values in given range - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count subarrays with max values in given range

Last Updated : 25 Mar, 2025

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.

[Naive Approach] Generate All Subarrays - O(n^2) Time and O(n) Space

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].


Output
14

[Expected Approach] Using Two Pointers - O(n) Time and O(1) Space

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:

  • Initialize variables count, lastInvalid, and lastValid to track valid subarrays and handle elements outside the range efficiently.
  • Iterate through the array while updating lastInvalid when encountering an element greater than the upper bound r.
  • Update lastValid whenever an element falls within the range l to r, marking the latest valid position.
  • Compute the number of valid subarrays ending at the current index by subtracting lastInvalid from lastValid.
  • Accumulate this count into the total count, ensuring all valid subarrays are considered efficiently.
  • Continue processing until the entire array is traversed and return the final count.

Output
14
Comment
Article Tags: