MediumArraysSliding WindowTwo Pointers

Longest Mountain in Array

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now