519/670

519. Longest Mountain in Array

Medium

You are given an integer array arr. A contiguous stretch of arr is a mountain when it is at least 3 elements long and, reading left to right, it strictly rises to a single highest point (the peak) and then strictly falls — both the rising part and the falling part must be non-empty, and equal neighbors break a mountain.

Return the length of the longest mountain contained in arr, or 0 if the array holds no mountain at all.

Follow-up: can you do it in one pass and O(1) extra space?

Example 1 — the longest mountainarr = [2, 1, 4, 7, 3, 2, 5]. The gold slice [1, 4, 7, 3, 2] strictly rises to the peak 7 and strictly falls afterwards — a mountain of length 5. The 5 at the end starts a new climb but never gets a downhill side.
2147325peak0123456index

Example 1:

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

Output: 5

Explanation: The slice [1, 4, 7, 3, 2] climbs 1 → 4 → 7 and then drops 7 → 3 → 2, so it is a mountain of length 5. No longer mountain exists.

Example 2:

Input: arr = [2, 2, 2]

Output: 0

Explanation: Equal neighbors never rise or fall strictly, so there is no mountain.

Constraints:

  • 1 ≤ arr.length ≤ 10⁴
  • 0 ≤ arr[i] ≤ 10⁴

Hints:

A mountain is an uphill run glued to a downhill run at a shared peak. From any starting index you can greedily walk up while values strictly rise, then walk down while they strictly fall — if both walks moved, you found a mountain.

For one pass, keep two counters: `up` = length of the strictly-rising run ending at i, `down` = length of the strictly-falling run ending at i. A flat step, or a rise that comes after a fall, starts a fresh mountain. Whenever both counters are positive, up + down + 1 is a candidate answer.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

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

Expected output: 5