Ctrl K

Longest Ridge on the Route

Medium
A hiking route is given as the array heights, the elevations of its points in order. Call a contiguous stretch of the route a *ridge* if it has at least 3 points and the elevation first strictly rises and then strictly falls. The summit cannot be the first or the last point of the stretch: there must be both a climb and a descent. Return the length of the longest ridge (the number of points in it), or 0 if the route has no ridge. Try to do it in a single pass with O(1) extra memory.
Example 1
heights=[3, 1, 2, 6, 8, 4, 4, 2] → 5

The ridge 1, 2, 6, 8, 4 climbs to 8 and drops to 4. The next 4 is flat ground, which ends the descent. Length 5.

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

The route only climbs and never descends, so there is no ridge and the answer is 0.

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

There are ridges 0, 5, 0 (length 3) and 0, 3, 2, 1, 0 (length 5). They share the 0 between them, which is fine.

Constraints
  • 1 ≤ len(heights) ≤ 10⁵
  • 0 ≤ heights[i] ≤ 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWord Growth Chain MediumStrongest Product Team MediumTwo Lost, the Rest Shifted MediumSpells Without Neighbors MediumSums of Staircase Runs Medium
loading Python…
Input
heights=[3, 1, 2, 6, 8, 4, 4, 2]
Expected
5

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