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 in Array INPUT Array Visualization: 2 1 4 7 (peak) 3 2 5 Input Array: 2 1 4 7 3 2 5 indices: 0 1 2 3 4 5 6 ALGORITHM STEPS 1 Find Peak Points arr[i-1] < arr[i] > arr[i+1] 2 Expand Left Count increasing elements 3 Expand Right Count decreasing elements 4 Track Maximum Update longest mountain One Pass Detection: Peak at i=3 (value=7) Left: 1 --> 4 --> 7 (up=2) Right: 7 --> 3 --> 2 (down=2) Mountain: 1+1+2+2 = 5 FINAL RESULT Longest Mountain Found: 2 1 4 7 3 2 Subarray [1,4,7,3,2]: 1 4 7 3 2 Output: 5 OK - Valid Mountain! Key Insight: One Pass Solution scans left-to-right, tracking UP counts (increasing) and DOWN counts (decreasing). When direction changes from UP to DOWN, we have a potential peak. Mountain length = up + down + 1. Time: O(n), Space: O(1) - No extra arrays needed, just track counts as we traverse. TutorialsPoint - Longest Mountain in Array | One Pass Solution
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