Problem Description
Given an array, find the length of the longest subarray that is a mountain. A mountain is defined as a subarray with at least three elements where there exists an index i (0-indexed) such that:
- arr[0] < arr[1] < ... < arr[i-1] < arr[i]
- arr[i] > arr[i+1] > ... > arr[arr.length - 1] Return the length of the longest such subarray; if none exists, return 0.
Key Insights
- A mountain requires a strictly increasing sequence followed by a strictly decreasing sequence.
- The peak element cannot be the first or last element.
- Identify the peak and expand left and right to determine the bounds of the mountain.
- Use a one-pass scan to detect peaks and measure the length of the mountain from each found peak.
- Maintain O(1) extra space by using index variables only.
Space and Time Complexity
Time Complexity: O(n) - We go through the array while scanning for peaks. Space Complexity: O(1) - Only constant extra space is used.
Solution
We solve the problem using a single pass through the array. For every element, we check if it can be considered a mountain peak (i.e. it is greater than its previous and next element). Once a peak is found, we expand to the left to count how many elements are in the strictly increasing sequence and to the right for the strictly decreasing sequence. The mountain length is the sum of these counts plus one (for the peak itself). Keep track of the maximum mountain length encountered. The main challenge is correctly handling edge cases where the mountain might extend beyond adjacent equal values or the array boundaries.