Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int countMatchingSubarrays(const vector<int>& nums, const vector<int>& pattern) {
- int matchingSubarrays = 0; // Variable to store the count of matching subarrays
- int numsSize = nums.size(); // Size of the input array nums
- int patternSize = pattern.size(); // Size of the pattern array
- // Loop over all subarrays of length equal to pattern length
- for (int i = 0; i <= numsSize - patternSize; ++i) {
- bool isValid = true; // Flag to check if the current subarray matches the pattern
- // Loop through the pattern to compare with the subarray starting at index i
- for (int j = 1; j < patternSize; ++j) {
- // Pattern indicates nums[i + j] should be greater than nums[i + j - 1]
- if (pattern[j] == 1 && nums[i + j] <= nums[i + j - 1]) {
- isValid = false;
- break;
- }
- // Pattern indicates nums[i + j] should be equal to nums[i + j - 1]
- if (pattern[j] == 0 && nums[i + j] != nums[i + j - 1]) {
- isValid = false;
- break;
- }
- // Pattern indicates nums[i + j] should be less than nums[i + j - 1]
- if (pattern[j] == -1 && nums[i + j] >= nums[i + j - 1]) {
- isValid = false;
- break;
- }
- }
- // If the subarray matches the pattern, increment the count
- if (isValid) {
- ++matchingSubarrays;
- }
- }
- return matchingSubarrays; // Return the total count of matching subarrays
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement