Problem 247788 · easy · Phase 02 Linear Data Structures

Count the Peaks

arrays · iteration · neighbours

An elevation profile of a hiking trail is given as heights. A peak is a position that is strictly higher than both its immediate neighbours. The first and last positions can never be peaks. Return the number of peaks.

Examples

Input:  heights = [1, 3, 2, 4, 1]
Output: 2
Explanation: 3 (index 1) and 4 (index 3) are peaks.

Input:  heights = [1, 2, 3]
Output: 0

Constraints

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

Goals

  • Compare each interior element with both neighbours
  • Use index bounds so the first and last elements are never peaks
Starting Python…