# Leetcode 2444. Count Subarrays With Fixed Bounds
###### tags: `leetcode` `daily` `two pointer`
[題目連結](https://xxxx/)
# Method two pointer
:::info
:bulb: **作法講解**:
## **Concept**
we use three pointer to define the window.
* **"i"** means current right position.
* **"l1"** means **"nums[i ~ l1]"** includes minK or maxK.
* **"l2"** means **"nums[i ~ l2]"** includes minK and maxK.
when the right position is **"i"**
the number of fixed-bound subarrays is **"l2 - l1"**
```cpp=
l2 l1 i
x x x x x x x x x x x
```
* * *
based on the above concept.
Initialize,
* **"l1"** set to 0
* **"l2"** set to 0
* **"min_cnt"** set to 0
* **"max_cnt"** set to 0
* **"output"** set to 0
we scan the index **"i"** from start to end in nums.
we may meet below two case,
- case 1: **"nums[i]"** is bigger than maxK or **"nums[i]"** is less than minK
- **"l1"** set to **"i+1"**
- **"l2"** set to **"i+1"**
- **"min_cnt"** set to 0
- **"max_cnt"** set to 0
- case 2: **"nums[i]"** is between minK and maxK
- if **"nums[i]"** is minK, increase **"min_cnt"**
- if **"nums[i]"** is maxK, increase **"max_cnt"**
- when **"min_cnt"** > 0 and **"max_cnt"** > 0,
check **"nums[l1]"** value, decrease **"min_cnt"** or **"max_cnt"**
move the l1 to next value,
until **"min_cnt"** or **"max_cnt"** is 0
:::
TC: O(N) SC: O(1)
完整程式碼
```cpp=
class Solution {
public:
typedef long long ll;
long long countSubarrays(vector<int>& nums, int minK, int maxK) {
int n = nums.size();
int min_cnt = 0;
int max_cnt = 0;
int l1 = 0;
int l2 = 0;
ll output = 0;
// l2 l1 i
// x x x x x x x x
for(int i = 0 ; i < n ; i++) {
if((nums[i] < minK) || (nums[i] > maxK)) {
l1 = i + 1;
l2 = i + 1;
min_cnt = 0;
max_cnt = 0;
continue;
}
min_cnt += (nums[i] == minK);
max_cnt += (nums[i] == maxK);
while(min_cnt && max_cnt) {
min_cnt -= (nums[l1] == minK);
max_cnt -= (nums[l1] == maxK);
l1++;
}
output += (l1 - l2);
}
return output;
}
};
```