




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.
1class Solution {
2    public int longestMountain(int[] arr) {
3        int n = arr.length;
4        if (n < 3) return 0;
5        int maxLen = 0;
6        for (int i = 1; i < n - 1; ) {
7            if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) {
8                int left = i - 1, right = i + 1;
9                while (left > 0 && arr[left] > arr[left - 1]) left--;
10                while (right < n - 1 && arr[right] > arr[right + 1]) right++;
11                maxLen = Math.max(maxLen, right - left + 1);
12                i = right + 1;
13            } else {
14                i++;
15            }
16        }
17        return maxLen;
18    }
19
20    public static void main(String[] args) {
21        Solution sol = new Solution();
22        int[] arr = {2, 1, 4, 7, 3, 2, 5};
23        System.out.println(sol.longestMountain(arr));
24    }
25}The Java version encapsulates the solution in a class method. It processes the array to locate peaks and then checks the maximum mountain size via an expanding approach. The loop continues by updating index i to skip processed segments.
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
This C implementation leverages variable ascent to track climbing phase and descent for descent. A valid mountain forms when both ascent and descent qualities exceed zero. The inner loop skips flat sections to align with mountain criteria.