




Sponsored
Sponsored
This approach involves scanning the array to find all the peaks and then measuring the length of a mountain centered at each peak. We use two traversals: one forward scan to detect peaks and another scan to calculate maximum width of the mountains.
Time complexity is O(n) as each element is processed at most twice. Space complexity is O(1) since we use only a few extra variables.
1function longestMountain(arr) {
2    const n = arr.length;
3    if (n < 3) return 0;
4    let maxLen = 0;
5    let i = 1;
6    while (i < n - 1) {
7        if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) {
8            let left = i - 1;
9            let right = i + 1;
10            while (left > 0 && arr[left] > arr[left - 1]) left--;
11            while (right < n - 1 && arr[right] > arr[right + 1]) right++;
12            maxLen = Math.max(maxLen, right - left + 1);
13            i = right;
14        } else {
15            i++;
16        }
17    }
18    return maxLen;
19}
20
21const arr = [2, 1, 4, 7, 3, 2, 5];
22console.log(longestMountain(arr));In JavaScript, the function iterates through the array using a mix of traditional loops and logical checks to identify valid peaks followed by extents calculation, updating max length accordingly.
This approach uses a single pass through the array to maintain both ascent and descent counts, swapping them at every ascent reset. A separate check is performed to ensure valid peaks for mountain length calculations.
Time complexity is O(n) for a single well-managed loop, with O(1) space thanks to a fixed set of variables.
1
JavaScript's style embraces a function-driven logic, following a singular indexing gesture to accomplish mountain recognition and calculate associated lengths when present.