




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.
1using System;
2
3class Program {
4    public static int LongestMountain(int[] arr) {
5        int n = arr.Length;
6        if (n < 3) return 0;
7        int maxLen = 0;
8        for (int i = 1; i < n - 1;) {
9            if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) {
10                int left = i - 1, right = i + 1;
11                while (left > 0 && arr[left] > arr[left - 1]) left--;
12                while (right < n - 1 && arr[right] > arr[right + 1]) right++;
13                maxLen = Math.Max(maxLen, right - left + 1);
14                i = right;
15            } else {
16                i++;
17            }
18        }
19        return maxLen;
20    }
21
22    static void Main() {
23        int[] arr = {2, 1, 4, 7, 3, 2, 5};
24        Console.WriteLine(LongestMountain(arr));
25    }
26}The C# program iterates through the given array, checking the mountain condition at every index. It keeps track of the longest subarray found and continues processing efficiently using the loop control variable i.
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.