Problem 276939 · medium · Level 02 Linear Data Structures

Bumps and Dips on the Cycle Path

arrays · neighbours · runs

A cycle path's height profile is heights, one reading per metre. A hill is a spot whose closest different readings on both sides are lower; a valley is a spot whose closest different readings on both sides are higher. A flat run of equal readings is a single hill or valley, counted once, and a spot with no different reading on one side is neither. Return how many hills and valleys the path has altogether.

Examples

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

Input:  heights = [9, 9, 7, 3, 3, 1]
Output: 0
Explanation: The path 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…