Tap here to switch tabs
Problem
Submissions

Problem: Count Hills and Valleys in an Array

med
30 min
Try to solve the Count Hills and Valleys in an Array problem.

Statement

Given an integer array nums, count how many hills and valleys it contains, and return that count.

For an index i, let the closest non equal element to the left of i be the first index l < i such that nums[l] != nums[i] and for every k with l < k < i, nums[k] == nums[i]. Similarly, let the closest non equal element to the right of i be the first index r > i such that nums[r] != nums[i] and for every k with i < k < r, nums[k] == nums[i].

Index i is a hill if both such neighbors exist and nums[i] is strictly greater than both of them. Index i is a valley if both such neighbors exist and nums[i] is strictly smaller than both of them.

If multiple consecutive indices have the same value and they form a single hill or a single valley with respect to their closest non equal neighbors, count that hill or valley only once.

Implement int countHillValley(self, nums) to return the total number of hills and valleys in nums.

Note: When determining hills and valleys, equal adjacent values are ignored by looking outward to the nearest different values.

Constraints:

  • 33 \leq nums.length 100\leq 100

  • 11 \leq nums[i] 100\leq 100

Tap here to switch tabs
Problem
Submissions

Problem: Count Hills and Valleys in an Array

med
30 min
Try to solve the Count Hills and Valleys in an Array problem.

Statement

Given an integer array nums, count how many hills and valleys it contains, and return that count.

For an index i, let the closest non equal element to the left of i be the first index l < i such that nums[l] != nums[i] and for every k with l < k < i, nums[k] == nums[i]. Similarly, let the closest non equal element to the right of i be the first index r > i such that nums[r] != nums[i] and for every k with i < k < r, nums[k] == nums[i].

Index i is a hill if both such neighbors exist and nums[i] is strictly greater than both of them. Index i is a valley if both such neighbors exist and nums[i] is strictly smaller than both of them.

If multiple consecutive indices have the same value and they form a single hill or a single valley with respect to their closest non equal neighbors, count that hill or valley only once.

Implement int countHillValley(self, nums) to return the total number of hills and valleys in nums.

Note: When determining hills and valleys, equal adjacent values are ignored by looking outward to the nearest different values.

Constraints:

  • 33 \leq nums.length 100\leq 100

  • 11 \leq nums[i] 100\leq 100