[LeetCode] Continuous Subarrays

6911. Continuous Subarrays

You are given a 0-indexed integer array nums. A subarray of nums is called continuous if:

  • Let i, i + 1, …, j be the indices in the subarray. Then, for each pair of indices i <= i1, i2 <= j, 0 <= |nums[i1] - nums[i2]| <= 2.

Return the total number of continuous subarrays.

A subarray is a contiguous non-empty sequence of elements within 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
29
30
31
32
33
34
35
class Solution {
public:
long long continuousSubarrays(vector<int>& nums) {
map<long long, long long> freq;
auto ok = [&]() {
if(freq.size() > 3) return false;
if(freq.size() == 0) return true;
long long mi = begin(freq)->first, ma = prev(end(freq))->first;
return ma - mi <= 2;
};
auto incr = [&](int x) {
freq[x] += 1;
};
auto decr = [&](int x) {
if(--freq[x] == 0) freq.erase(x);
};
long long res = 0, l = 0, r = 0, n = nums.size();
while(r < n) {
while(r < n and ok()) {
incr(nums[r++]);
if(ok()) res += (r - l);
else {
break;
}
}
bool flag = false;
while(l < n and !ok()) {
flag = true;
decr(nums[l++]);
}
if(flag) res += (r - l);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/02/PS/LeetCode/continuous-subarrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.