Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- int sawtooth(const std::vector<int> &nums);
- bool satisfySawToothPredicate(const std::vector<int> &nums, int idx);
- int main()
- {
- std::vector<int> nums1{9, 8, 7, 6};
- std::vector<int> nums2{1, 2, 3, 4};
- std::vector<int> nums3{1, 2, 1};
- std::vector<int> nums4{1, 2, 1, 1, 1, 2, 1};
- std::vector<int> nums5{1, 1, 1, 1, 1, 1};
- std::cout << "sawtooth(nums1) = " << sawtooth(nums1) << std::endl;
- std::cout << "sawtooth(nums2) = " << sawtooth(nums2) << std::endl;
- std::cout << "sawtooth(nums3) = " << sawtooth(nums3) << std::endl;
- std::cout << "sawtooth(nums4) = " << sawtooth(nums4) << std::endl;
- std::cout << "sawtooth(nums5) = " << sawtooth(nums5) << std::endl;
- }
- int sawtooth(const std::vector<int> &nums)
- {
- int left, right, size;
- int amountOfSubArraysWhichAreSawTooths;
- size = nums.size();
- left = right = 0;
- amountOfSubArraysWhichAreSawTooths = 0;
- for (right = 1; right < size; ++right)
- {
- if ((right - left <= 1 && nums[right] != nums[left]) ||
- (right - left > 1 && satisfySawToothPredicate(nums, right)))
- {
- amountOfSubArraysWhichAreSawTooths = amountOfSubArraysWhichAreSawTooths + right - left;
- }
- else
- {
- left = (left + 1 == right ? right : --right);
- }
- }
- return amountOfSubArraysWhichAreSawTooths;
- }
- bool satisfySawToothPredicate(const std::vector<int> &nums, int idx)
- {
- return (nums[idx] - nums[idx - 1]) * (nums[idx - 1] - nums[idx - 2]) < 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement