Count the number of contiguous subarrays whose minimum equals a given lower bound and whose maximum equals a given upper bound.
Count Subarrays With Fixed Bounds
Given an integer array nums and two integers minK and maxK, count how many contiguous subarrays satisfy all of the following:
- every element in the subarray lies within the inclusive range
[minK, maxK] - the minimum element in the subarray is exactly
minK - the maximum element in the subarray is exactly
maxK
Return the total number of such subarrays.
A subarray is a contiguous non-empty segment of the array.
The key challenge is to count all valid subarrays efficiently without checking every possible subarray.
Input Format
nums: an integer arrayminK: the required minimum valuemaxK: the required maximum value
Output Format
- Return a single integer: the number of subarrays whose minimum is
minKand maximum ismaxKwhile all values stay within[minK, maxK].
Constraints
- Subarrays must be contiguous and non-empty.
- Values outside
[minK, maxK]invalidate any subarray that includes them. - Count all valid subarrays, including overlapping ones.
Example 1
Input
nums = [1,3,5,2,7,5], minK = 1, maxK = 5
Output
2
Explanation
The valid subarrays are [1,3,5] and [1,3,5,2].
Example 2
Input
nums = [1,1,1,1], minK = 1, maxK = 1
Output
10
Explanation
Every non-empty subarray is valid. There are 4 + 3 + 2 + 1 = 10 subarrays.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.