Count Subarrays With Fixed Bounds

Hard

Description

Given an integer array nums and two integers minK and maxK, return the number of fixed-bound subarrays. A subarray is fixed-bound if its minimum is minK and maximum is maxK.

Examples

Input:nums = [1,3,5,2,7,5], minK = 1, maxK = 5
Output:2
Explanation:

Subarrays [1,3,5] and [1,3,5,2] are fixed-bound.

Input:nums = [2,4,2,6,2,4,2], minK = 2, maxK = 4
Output:6
Explanation:

The valid fixed-bound subarrays are: [2,4] (positions 0-1), [4,2] (positions 1-2), [2,4,2] (positions 0-2), [2,4] (positions 5-6), [4,2] (positions 6-7), and [2,4,2] (positions 4-6). Each subarray has minimum 2 and maximum 4. Note that subarrays containing 6 cannot be fixed-bound since 6 > maxK.

Input:nums = [3,3,3,3,3], minK = 3, maxK = 3
Output:15
Explanation:

When minK equals maxK, all elements must equal this value for a valid subarray. Since all elements are 3, every possible subarray is fixed-bound. With 5 elements, there are 5*(5+1)/2 = 15 total subarrays: 5 of length 1, 4 of length 2, 3 of length 3, 2 of length 4, and 1 of length 5.

Constraints

  • 2 ≤ nums.length ≤ 10⁵
  • 1 ≤ nums[i], minK, maxK ≤ 10⁶

Ready to solve this problem?

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