Longest Mountain in Array - Problem

You may recall that an array arr is a mountain array if and only if:

  • arr.length >= 3
  • There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that:
    • arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
    • arr[i] > arr[i + 1] > ... > arr[arr.length - 1]

Given an integer array arr, return the length of the longest subarray which is a mountain.

Return 0 if there is no mountain subarray.

Input & Output

Example 1 — Basic Mountain
$ Input: arr = [2,1,4,7,3,2,5]
Output: 5
💡 Note: The longest mountain is [1,4,7,3,2] with length 5. It goes up: 1<4<7, then down: 7>3>2.
Example 2 — No Mountain
$ Input: arr = [2,2,2]
Output: 0
💡 Note: No mountain exists because all elements are equal. A mountain requires strictly increasing then decreasing.
Example 3 — Multiple Mountains
$ Input: arr = [0,1,2,3,4,5,4,3,2,1,0]
Output: 11
💡 Note: The entire array forms one mountain: 0<1<2<3<4<5>4>3>2>1>0, length 11.

Constraints

  • 1 ≤ arr.length ≤ 1000
  • 0 ≤ arr[i] ≤ 104

Visualization

Tap to expand
Longest Mountain Problem: [2,1,4,7,3,2,5]2147325Mountain: 1 < 4 < 7 > 3 > 2Strictly increasing, then strictly decreasingDefinition: Mountain = Up then Down (length ≥ 3)Output: 5 (length of longest mountain)
Understanding the Visualization
1
Input
Array with potential mountain patterns
2
Process
Find subarrays that go strictly up then strictly down
3
Output
Length of longest valid mountain
Key Takeaway
🎯 Key Insight: A valid mountain must have both strictly increasing and strictly decreasing parts
Asked in
Facebook 8 Google 5
67.9K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen