[LeetCode] Count Subarrays With Fixed Bounds

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.

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
class Solution {
public:
long long countSubarrays(vector<int>& A, int mi, int ma) {
deque<int> mipos, mapos, none;
long long res = 0, n = A.size();
for(int i = 0; i < n; i++) {
if(A[i] == mi) mipos.push_back(i);
if(A[i] == ma) mapos.push_back(i);
if(A[i] < mi or A[i] > ma) none.push_back(i);
}
none.push_back(n);
for(int i = 0; i < n; i++) {
while(mipos.size() and mipos[0] < i) mipos.pop_front();
while(mapos.size() and mapos[0] < i) mapos.pop_front();
while(none.size() and none[0] < i) none.pop_front();
if(mi <= A[i] and A[i] <= ma) {
long long last = -1, nonep = none[0];
if(mipos.size() and mapos.size()) last = max(mipos[0], mapos[0]);
if(last == -1) continue;
if(last < nonep) {
long long len = nonep - last;
res += len;
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/16/PS/LeetCode/count-subarrays-with-fixed-bounds/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.