Number of Subarrays with Bounded Maximum

Medium

Description

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 element is in the range [left, right].

Examples

Input:nums = [2,1,4,3], left = 2, right = 3
Output:3
Explanation:

[2], [2,1], [3] qualify.

Input:nums = [5,7,2,9,1,6], left = 4, right = 8
Output:8
Explanation:

The qualifying subarrays are: [5] (max=5), [7] (max=7), [5,7] (max=7), [7,2] (max=7), [5,7,2] (max=7), [6] (max=6), [1,6] (max=6), and [2,9,1,6] would not qualify because max=9 > 8, but [6] at the end qualifies. Total: 8 subarrays where the maximum element is between 4 and 8 inclusive.

Input:nums = [1,1,1], left = 3, right = 5
Output:0
Explanation:

No subarrays qualify because all elements are 1, which is less than the left bound of 3. Every possible subarray [1], [1,1], [1,1,1] has a maximum value of 1, which is not in the range [3,5].

Constraints

  • 1 ≤ nums.length ≤ 10^5
  • 0 ≤ nums[i] ≤ 10^9

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!