Skip to content

The Longest Mountain In Place

A CONTIGUOUS run is a mountain when it strictly rises to a single peak and then strictly falls. Both sides must be non-empty, so the run has length at least 3.

Print the length of the longest mountain, or 0 if there is none.

2 1 4 7 3 2 5 -> 5 the run 1 4 7 3 2 1 2 3 -> 0 no fall, so no mountain

Problem 455 asks the same question about SUBSEQUENCES, where elements may be skipped and two O(n^2) passes are the answer. Here the run must be contiguous, which makes it a scan rather than a table.

Walk the interior looking for a peak, meaning a[i-1] < a[i] > a[i+1]. From each peak, extend left while the values keep rising and right while they keep falling, and record the width.

The detail that makes it O(n) rather than O(n^2): after measuring a mountain, resume the outer scan at its RIGHT EDGE, not at the next index. Anything between the peak and that edge is strictly falling, so it cannot be a peak itself, and rescanning it repeats work already done.

Two boundaries matter. A plateau is never a mountain, since both sides must be STRICT, so 2 2 2 answers 0 and 1 2 2 1 also answers 0. And the peak must be an interior index, so a monotonic array answers 0 rather than its own length.

Constraints - `1 ≤ n ≤ 200000` - `-1000000 ≤ value ≤ 1000000`