Show problems as
Classic problem #845MediumArrayTwo PointersDynamic ProgrammingEnumeration

Longest Mountain in Array

Real-world version: Longest Ridge in the Profile
Tracked in this browser only
Read Longest Mountain in Array on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstSliding Window · Arrays, animated step by step

Ground heights along a track are given as arr.

A ridge is a stretch of at least three heights that rises strictly for a while and then falls strictly for a while: there is a position inside it, neither end, where everything before rises strictly up to it and everything after falls strictly away from it.

Return the length of the longest ridge, or 0 when the track holds none.

Examples

Example 1

Input
arr = [3, 8, 14, 9, 4, 4, 11, 2]
Output
5

The heights rise 3, 8, 14 and then fall 9, 4, which is a ridge of five. The fall stops at the level pair of fours, so the ridge cannot reach further.

Example 2

Input
arr = [1, 2, 3, 4, 5]
Output
0

The track only rises, so there is no peak and no ridge.

Example 3

Input
arr = [1, 2, 2, 1]
Output
0

The two level heights in the middle mean neither is a peak, since a peak needs its neighbours strictly lower.

Constraints

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

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def longest_mountain(arr: list[int]) -> int:
Java
public int longestMountain(int[] arr)