Longest Mountain in Array

An array is a **mountain** if it has length at least 3 and there is an index `i` with `0 < i < arr.length - 1` such that `arr[0] < arr[1] < ... < arr[i]` and `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`. Given an integer array `arr`, return the length of the longest subarray that is a mountain, or `0` if there is none.

30:00

Longest Mountain in Array
medium
Free written solution
Topics
Companies

An array is a mountain if it has length at least 3 and there is an index i with 0 < i < arr.length - 1 such that arr[0] < arr[1] < ... < arr[i] and arr[i] > arr[i + 1] > ... > arr[arr.length - 1]. Given an integer array arr, return the length of the longest subarray that is a mountain, or 0 if there is none.

Example 1:
Input: {"arr":[2,1,4,7,3,2,5]}
Output: 5
Constraints:
  • 1≤arr.length≤1041 \leq \text{arr.length} \leq 10^4

  • 0≤arr[i]≤1040 \leq \text{arr}[i] \leq 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

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

A mountain goes strictly up, then strictly down, and is at least 3 long. Walk the 7 heights once with two pointers: base marks a left foot and end walks the slope. best = 0.

heights (green = uphill, amber = peak, blue = downhill)

2147325
base = -
end = -
window = 0
best = 0
mountains = 0
Variables
VariableValue
n7
best0
DepthFunction Call
Stack empty
0/16