2444. Count Subarrays With Fixed Bounds
T: O(n)
S: O(1)
```java
class Solution {
public long countSubarrays(int[] nums, int minK, int maxK) {
int n = nums.length;
int leftBound = -1;
int minIndex = -1;
int maxIndex = -1;
long result = 0;
for (int right = 0; right < n; right++) {
int rightNum = nums[right];
if (rightNum < minK || rightNum > maxK) {
leftBound = right;
}
if (rightNum == minK) {
minIndex = right;
}
if (rightNum == maxK) {
maxIndex = right;
}
result += Math.max(0, Math.min(minIndex, maxIndex) - leftBound);
}
return result;
}
}
/**
T: O(n)
S: O(1)
2 points, not sliding win actually, beacuse left not continuously move++
[1,3,5,2,7,5]
r
l
0. 1 2
if value is between minK and maxK, it's ok, can in the subarray
min = 1 max = 5
0 1 2 3 4
[2,3,4,1,5]
these are all good -> to in the subarrays
so min(indexOfMinK, indexOfMinK) = 3
3 - leftbound(-1) = 4
these subarrays:
[2,3,4,1,5] -> thats why subarray count is (min index - leftboud)
[3,4,1,5]
[4,1,5]
[1,5]. (this is why leftbound has to be -1)!
focus on right end
which includes minK and maxK
if (we both have mink maxk in this subarray, the subarray count will be min(indexMinK, indexMaxK)) - leftbound(-1)
leftbound means not include minK and maxK
*/
```
Last updated