Advertisement
asdfg0998

asdf

Sep 15th, 2024
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. int countMatchingSubarrays(const vector<int>& nums, const vector<int>& pattern) {
  2.     int matchingSubarrays = 0;  // Variable to store the count of matching subarrays
  3.     int numsSize = nums.size(); // Size of the input array nums
  4.     int patternSize = pattern.size(); // Size of the pattern array
  5.    
  6.     // Loop over all subarrays of length equal to pattern length
  7.     for (int i = 0; i <= numsSize - patternSize; ++i) {
  8.         bool isValid = true;  // Flag to check if the current subarray matches the pattern
  9.        
  10.         // Loop through the pattern to compare with the subarray starting at index i
  11.         for (int j = 1; j < patternSize; ++j) {
  12.             // Pattern indicates nums[i + j] should be greater than nums[i + j - 1]
  13.             if (pattern[j] == 1 && nums[i + j] <= nums[i + j - 1]) {
  14.                 isValid = false;
  15.                 break;
  16.             }
  17.             // Pattern indicates nums[i + j] should be equal to nums[i + j - 1]
  18.             if (pattern[j] == 0 && nums[i + j] != nums[i + j - 1]) {
  19.                 isValid = false;
  20.                 break;
  21.             }
  22.             // Pattern indicates nums[i + j] should be less than nums[i + j - 1]
  23.             if (pattern[j] == -1 && nums[i + j] >= nums[i + j - 1]) {
  24.                 isValid = false;
  25.                 break;
  26.             }
  27.         }
  28.        
  29.         // If the subarray matches the pattern, increment the count
  30.         if (isValid) {
  31.             ++matchingSubarrays;
  32.         }
  33.     }
  34.  
  35.     return matchingSubarrays;  // Return the total count of matching subarrays
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement