Problem
You are given an integer array nums
and two integers minK
and maxK
.
A fixed-bound subarray of nums
is a subarray that satisfies the following conditions:
- The minimum value in the subarray is equal to
minK
. - The maximum value in the subarray is equal to
maxK
.
Return the number of fixed-bound subarrays.
A subarray is a contiguous part of an array.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Count valid subarrays
This problem involves finding subarrays that meet specific constraints, where the minimum value equals minK
and the maximum value equals maxK
. The strategy is to efficiently traverse the array to count valid subarrays rather than using brute-force methods.
So, first we track bounds:
- Maintain
lastMinK
to track the last occurrence ofminK
. - Maintain
lastMaxK
to track the last occurrence ofmaxK
. - Use a
lastInvalid
pointer to track the last index that invalidates the condition (like elements outside the range[minK, maxK]
).
Count the valid subarrays:
- As we iterate through the array, calculate how far back we can create valid subarrays based on
lastMinK
andlastMaxK
.
So, instead of checking bounds for every possible subarray, maintain positions of these essential values (minK
and maxK
) to reduce redundant checks.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, since we traverse the list once while maintaining constant-time updates for pointers. - 🧺 Space complexity:
O(1)
, as we use only a few integer variables for tracking positions, independent of the input size.