Advertisement
yarin0600

sawtooth

Nov 24th, 2023
648
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. int sawtooth(const std::vector<int> &nums);
  5. bool satisfySawToothPredicate(const std::vector<int> &nums, int idx);
  6.  
  7. int main()
  8. {
  9.    std::vector<int> nums1{9, 8, 7, 6};
  10.    std::vector<int> nums2{1, 2, 3, 4};
  11.    std::vector<int> nums3{1, 2, 1};
  12.    std::vector<int> nums4{1, 2, 1, 1, 1, 2, 1};
  13.    std::vector<int> nums5{1, 1, 1, 1, 1, 1};
  14.    std::cout << "sawtooth(nums1) = " << sawtooth(nums1) << std::endl;
  15.    std::cout << "sawtooth(nums2) = " << sawtooth(nums2) << std::endl;
  16.    std::cout << "sawtooth(nums3) = " << sawtooth(nums3) << std::endl;
  17.    std::cout << "sawtooth(nums4) = " << sawtooth(nums4) << std::endl;
  18.    std::cout << "sawtooth(nums5) = " << sawtooth(nums5) << std::endl;
  19. }
  20.  
  21. int sawtooth(const std::vector<int> &nums)
  22. {
  23.    int left, right, size;
  24.    int amountOfSubArraysWhichAreSawTooths;
  25.  
  26.    size = nums.size();
  27.    left = right = 0;
  28.    amountOfSubArraysWhichAreSawTooths = 0;
  29.  
  30.    for (right = 1; right < size; ++right)
  31.    {
  32.       if ((right - left <= 1 && nums[right] != nums[left]) ||
  33.           (right - left > 1 && satisfySawToothPredicate(nums, right)))
  34.       {
  35.          amountOfSubArraysWhichAreSawTooths = amountOfSubArraysWhichAreSawTooths + right - left;
  36.       }
  37.       else
  38.       {
  39.          left = (left + 1 == right ? right : --right);
  40.       }
  41.    }
  42.    return amountOfSubArraysWhichAreSawTooths;
  43. }
  44.  
  45. bool satisfySawToothPredicate(const std::vector<int> &nums, int idx)
  46. {
  47.  
  48.    return (nums[idx] - nums[idx - 1]) * (nums[idx - 1] - nums[idx - 2]) < 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement