Problem 276939 · medium · Phase 02 Linear Data Structures

Hills and Valleys

arrays · neighbours · runs

A trail profile is given as heights. Position i is part of a hill if its nearest non-equal neighbours on both sides are lower, and part of a valley if they are both higher. Consecutive equal heights belong to the same hill or valley and are counted once. Return the total number of hills and valleys.

Examples

Input:  heights = [2, 4, 1, 1, 6, 5]
Output: 3
Explanation: 4 is a hill, the plateau 1, 1 is one valley, 6 is a hill.

Input:  heights = [6, 6, 5, 5, 4, 1]
Output: 0
Explanation: The trail only goes down.

Constraints

  • 0 <= len(heights) <= 10**5
  • Target: O(n) time.

Goals

  • Skip over runs of equal values when looking for neighbours
  • Count each plateau at most once
Starting Python…