MediumArraysSliding WindowTwo Pointers

1 approach, code in every language

Problem description

A mountain inside an array is a run of at least three elements that first climbs strictly upward to a single peak and then falls strictly downward. Given an integer array, determine the length of the longest such mountain, and return 0 when the array holds no mountain at all.

The trick is to treat every strict peak as the crest of a potential mountain and stretch outward in both directions as long as the strict up-then-down shape holds.

Example 1

Input: arr = [2,1,4,7,3,2,5]

Output: 5

The stretch 1,4,7,3,2 rises to the peak 7 and then descends, spanning five elements.

Example 2

Input: arr = [2,2,2]

Output: 0

No element ever rises above its neighbours, so there is no valid peak and no mountain.

Constraints

  • 1 ≤ arr.length ≤ 10^4
  • 0 ≤ arr[i] ≤ 10^4

After the pattern

Now solve one you haven't seen.

Longest Ridge in the Profile is our own problem on the technique behind Longest Mountain in Array: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free