Skip to main content
Back to problems
#795
Medium Algorithms

Number of subarrays with bounded maximum

Array Two Pointers
54.7% acceptance
Feb 21, 2026
2449
135
Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right]. The test cases are generated so that the answer will fit in a 32-bit integer.

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
/*
 * Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right].
 * The test cases are generated so that the answer will fit in a 32-bit integer.
 * Example 1:
 * Input: nums = [2,1,4,3], left = 2, right = 3
 * Output: 3
 * Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].
 * Example 2:
 * Input: nums = [2,9,2,5,6], left = 2, right = 8
 * Output: 7
 * Constraints:
 * 1 <= nums.length <= 105
 * 0 <= nums[i] <= 109
 * 0 <= left <= right <= 109
 */
impl Solution {
  pub fn num_subarray_bounded_max(nums: Vec<i32>, left: i32, right: i32) -> i32 {
    fn count_le(nums: &[i32], bound: i32) -> i32 {
      let mut total = 0i32;
      let mut curr = 0i32;
      for &x in nums {
        if x <= bound { curr += 1; } else { curr = 0; }
        total += curr;
      }
      total
    }
    count_le(&nums, right) - count_le(&nums, left - 1)
  }
}