Skip to content

2210. Count Hills and Valleys in an Array 👍

  • Time: $O(n)$
  • Space: $O(1)$
 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 ans = 0;
    int left = nums[0];

    for (int i = 1; i + 1 < nums.size(); ++i)
      if (left < nums[i] && nums[i] > nums[i + 1] ||  // the hill
          left > nums[i] && nums[i] < nums[i + 1]) {  // the valley
        ++ans;
        left = nums[i];
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int countHillValley(int[] nums) {
    int ans = 0;
    int left = nums[0];

    for (int i = 1; i + 1 < nums.length; ++i)
      if (left < nums[i] && nums[i] > nums[i + 1] || // the hill
          left > nums[i] && nums[i] < nums[i + 1]) { // the valley
        ++ans;
        left = nums[i];
      }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def countHillValley(self, nums: list[int]) -> int:
    ans = 0
    left = nums[0]

    for i in range(1, len(nums) - 1):
      if (left < nums[i] and nums[i] > nums[i + 1] or  # the hill
              left > nums[i] and nums[i] < nums[i + 1]):  # the valley
        ans += 1
        left = nums[i]

    return ans