-
Notifications
You must be signed in to change notification settings - Fork 0
/
CountSubarraysWithFixedBounds.java
48 lines (40 loc) · 1.39 KB
/
CountSubarraysWithFixedBounds.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
2444. Count Subarrays With Fixed Bounds
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.
Example 1:
Input: nums = [1,3,5,2,7,5], minK = 1, maxK = 5
Output: 2
Explanation: The fixed-bound 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 subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.
Constraints:
2 <= nums.length <= 105
1 <= nums[i], minK, maxK <= 106
*/
class CountSubarraysWithFixedBounds {
public long countSubarrays(int[] nums, int minK, int maxK) {
long ans = 0;
int j = -1;
int prevMinKIndex = -1;
int prevMaxKIndex = -1;
for (int i = 0; i < nums.length; ++i) {
if (nums[i] < minK || nums[i] > maxK)
j = i;
if (nums[i] == minK)
prevMinKIndex = i;
if (nums[i] == maxK)
prevMaxKIndex = i;
// any index k in [j + 1, min(prevMinKIndex, prevMaxKIndex)] can be the
// start of the subarray s.t. nums[k..i] satisfies the conditions
ans += Math.max(0, Math.min(prevMinKIndex, prevMaxKIndex) - j);
}
return ans;
}
}