You are given a 0-indexed integer array nums
. A hill is a peak element (greater than both of its neighboring elements), and a valley is a trough element (less than both of its neighboring elements). The first and last elements of nums
cannot be hills or valleys.
You need to return the number of hills and valleys in nums
.
Can the array have duplicate elements? Yes, the array can have duplicate elements.
Should we consider elements with the same value as their neighbors as potential hills or valleys? No, elements with the same value as their neighbors should not be considered as hills or valleys.
What is the range of the array length?
The length of nums
can range from 1 to 10^5.
What is the range of array elements?
The integers in nums
can range from -10^5 to 10^5.
def count_hills_and_valleys(nums):
if len(nums) < 3:
return 0
count = 0
for i in range(1, len(nums) - 1):
if nums[i] == nums[i - 1]:
continue
if nums[i] > nums[i - 1] and nums[i] > nums[i + 1]:
count += 1
elif nums[i] < nums[i - 1] and nums[i] < nums[i + 1]:
count += 1
return count
# Example usage:
nums = [2, 4, 1, 1, 6, 5]
print(count_hills_and_valleys(nums)) # Output: 2
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?