JJobsMoi
SoFi
SO

Longest Mountain in Array

Codingmedium

Problem

You are given an integer array heights representing the elevation profile of a hiking trail. A contiguous stretch of the trail is called a mountain if it satisfies all of the following:

  • It contains at least 3 elements.
  • There is a single peak index p inside the stretch (not at either end of the stretch) such that the elements strictly increase from the start of the stretch up to index p, and then strictly decrease from index p down to the end of the stretch.
  • Both the climb before the peak and the descent after the peak must contain at least one step — a mountain cannot be purely flat, purely rising, or purely falling.

Return the length of the longest mountain subarray that can be found in heights. If no valid mountain exists, return 0.

Notes:

  • The subarray must be contiguous.
  • Equal adjacent values break a mountain — a plateau anywhere in the stretch disqualifies it.
  • A subarray consisting only of an increasing run or only of a decreasing run does not count; both sides of the peak are required.

Examples

Example 1:

Input: heights = [4, 2, 5, 8, 6, 3, 7, 1]

Output: 5

Explanation:

The stretch [2, 5, 8, 6, 3] rises from index 1 to the peak at index 3 (value 8), then falls to index 5. Its length is 5, which is the longest mountain in the array. The values 7 and 1 near the end only form a two-element descent with nothing rising before it in a valid mountain shape.

Example 2:

Input: heights = [1, 1, 1, 1]

Output: 0

Explanation:

All values are equal, so there is no strict rise or fall anywhere, meaning no mountain can be formed.

Example 3:

Input: heights = [3, 5, 5, 2]

Output: 0

Explanation:

The segment rises from 3 to 5, but the repeated 5 creates a flat plateau instead of a distinct peak, and since the values never strictly increase into a single peak followed immediately by a strict decrease, no valid mountain exists.

Constraints

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

Solution

Loading editor…

Sign in to get AI feedback on your answer. Your work is saved while you do.

Sign in to evaluate