[LeetCode] Number of Subarrays That Match a Pattern I

3034. Number of Subarrays That Match a Pattern I

You are given a 0-indexed integer array nums of size n, and a 0-indexed integer array pattern of size m consisting of integers -1, 0, and 1.

A subarray nums[i..j] of size m + 1 is said to match the pattern if the following conditions hold for each element pattern[k]:

  • nums[i + k + 1] > nums[i + k] if pattern[k] == 1.
  • nums[i + k + 1] == nums[i + k] if pattern[k] == 0.
  • nums[i + k + 1] < nums[i + k] if pattern[k] == -1.

Return the count of subarrays in nums that match the pattern.

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
class Solution {
public:
int countMatchingSubarrays(vector<int>& nums, vector<int>& pattern) {
int res = 0;
for(int i = 0; i < nums.size(); i++) {
bool ok = true;
for(int j = 0; j < pattern.size() and ok; j++) {
if(i + j + 1 == nums.size()) ok = false;
else {
if(pattern[j] == 1) {
if(nums[i+j+1] > nums[i+j]) continue;
ok = false;
} else if(pattern[j] == 0) {
if(nums[i+j+1] == nums[i+j]) continue;
ok = false;
} else if(pattern[j] == -1) {
if(nums[i+j+1] < nums[i+j]) continue;
ok = false;
}
}
}
if(ok) res+=1;
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2024/02/11/PS/LeetCode/number-of-subarrays-that-match-a-pattern-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.