JuniorArray

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.

Example 1
        #
        # #
  #     # #
  #     # #
# #     # #
# # # # # #
2 4 1 1 6 5
Inputnums = [2,4,1,1,6,5]
Output3
There are 3 hills and valleys: index 1 is a hill, indices 2 and 3 are the same valley, and index 4 is a hill.
Example 2
# #
# # # #
# # # # #
# # # # #
# # # # #
# # # # # #
6 6 5 5 4 1
Inputnums = [6,6,5,5,4,1]
Output0
No index has closest non-equal neighbors that are both smaller or both larger, so there are 0 hills and valleys.

Constraints

  • 3 <= nums.length <= 100
  • 1 <= nums[i] <= 100

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate