Skip to content

Commit 78699c7

Browse files
committed
feat: add No.2444
1 parent 911a4f6 commit 78699c7

File tree

1 file changed

+101
-0
lines changed

1 file changed

+101
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
# 2444. Count Subarrays With Fixed Bounds
2+
3+
- Difficulty: Hard.
4+
- Related Topics: Array, Queue, Sliding Window, Monotonic Queue.
5+
- Similar Questions: Count Number of Nice Subarrays, Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit.
6+
7+
## Problem
8+
9+
You are given an integer array `nums` and two integers `minK` and `maxK`.
10+
11+
A **fixed-bound subarray** of `nums` is a subarray that satisfies the following conditions:
12+
13+
14+
15+
- The **minimum** value in the subarray is equal to `minK`.
16+
17+
- The **maximum** value in the subarray is equal to `maxK`.
18+
19+
20+
Return **the **number** of fixed-bound subarrays**.
21+
22+
A **subarray** is a **contiguous** part of an array.
23+
24+
 
25+
Example 1:
26+
27+
```
28+
Input: nums = [1,3,5,2,7,5], minK = 1, maxK = 5
29+
Output: 2
30+
Explanation: The fixed-bound subarrays are [1,3,5] and [1,3,5,2].
31+
```
32+
33+
Example 2:
34+
35+
```
36+
Input: nums = [1,1,1,1], minK = 1, maxK = 1
37+
Output: 10
38+
Explanation: Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.
39+
```
40+
41+
 
42+
**Constraints:**
43+
44+
45+
46+
- `2 <= nums.length <= 105`
47+
48+
- `1 <= nums[i], minK, maxK <= 106`
49+
50+
51+
52+
## Solution
53+
54+
```javascript
55+
/**
56+
* @param {number[]} nums
57+
* @param {number} minK
58+
* @param {number} maxK
59+
* @return {number}
60+
*/
61+
var countSubarrays = function(nums, minK, maxK) {
62+
var maxNum = 0;
63+
var minNum = 0;
64+
var left = 0;
65+
var res = 0;
66+
var start = 0;
67+
for (var right = 0; right < nums.length; right++) {
68+
if (nums[right] > maxK || nums[right] < minK) {
69+
maxNum = 0;
70+
minNum = 0;
71+
left = right + 1;
72+
start = right + 1;
73+
continue;
74+
}
75+
if (nums[right] === minK) minNum += 1;
76+
if (nums[right] === maxK) maxNum += 1;
77+
while (left < right && (
78+
(nums[left] !== minK && nums[left] !== maxK) ||
79+
(nums[left] === minK && minNum > 1) ||
80+
(nums[left] === maxK && maxNum > 1)
81+
)) {
82+
if (nums[left] === minK) minNum -= 1;
83+
if (nums[left] === maxK) maxNum -= 1;
84+
left += 1;
85+
}
86+
if (minNum >= 1 && maxNum >= 1) {
87+
res += left - start + 1;
88+
}
89+
}
90+
return res;
91+
};
92+
```
93+
94+
**Explain:**
95+
96+
Sliding window.
97+
98+
**Complexity:**
99+
100+
* Time complexity : O(n).
101+
* Space complexity : O(1).

0 commit comments

Comments
 (0)