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] ||  // hill
          left > nums[i] && nums[i] < nums[i + 1]) {  // 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] || // hill
          left > nums[i] && nums[i] < nums[i + 1]) { // valley
        ++ans;
        left = nums[i];
      }

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

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

    return ans