Ctrl K

Trail Peaks and Dips

Easy
Heights were measured at evenly spaced points along a hiking trail, giving the array heights. For a point i, take the nearest point to its left whose height differs from heights[i], and the nearest such point to its right. If both exist and both are lower than heights[i], point i sits on a **peak**; if both are higher, it sits in a **dip**. Neighbouring points of the same height form one flat stretch and count as a single peak or a single dip. Return the total number of peaks and dips on the trail.
Example 1
heights=[3, 5, 5, 2, 2, 4, 6] → 2

The flat stretch of two 5s is higher than its neighbours 3 and 2, so it is one peak. The two 2s are lower than 5 and 4, so they form one dip. That makes 2.

Example 2
heights=[1, 2, 3, 3, 4] → 0

The trail only climbs or stays level, so there are no peaks or dips.

Example 3
heights=[4, 1, 4, 1, 4] → 3

Dips at points 1 and 3 and a peak at point 2 give 3. The end points do not count: each lacks a neighbour on one side.

Constraints
  • 3 ≤ heights.length ≤ 100
  • 1 ≤ heights[i] ≤ 100
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPair With a Target Sum EasySqueeze Repeats Out of a Sorted Array EasyDrop the Unwanted Value EasySlot on a Sorted Shelf EasyAdd One to a Digit Array Easy
loading Python…
Input
heights=[3, 5, 5, 2, 2, 4, 6]
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 157 tests on the server, hidden ones included.