[LeetCode] Count Hills and Valleys in an Array

2210. Count Hills and Valleys in an Array

You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j].

Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index.

Return the number of hills and valleys in nums.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int countHillValley(vector<int>& nums) {
int res = 0, n = nums.size();
for(int i = 0; i < n; i++) {
int l = i - 1, r = i + 1;
if(i > 0 and nums[i] == nums[i-1]) continue;
while(l >= 0 and nums[l] == nums[i]) l--;
while(r < n and nums[r] == nums[i]) r++;
if(l < 0 or r >= n) continue;
if(nums[l] < nums[i] and nums[r] < nums[i]) res++;
else if(nums[l] > nums[i] and nums[r] > nums[i]) res++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/20/PS/LeetCode/count-hills-and-valleys-in-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.