#845

Longest Mountain in Array

Medium
ArrayTwo PointersDynamic ProgrammingEnumerationTwo PointersSliding WindowArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses a single pass to identify the mountains by tracking the lengths of increasing and decreasing sequences. This reduces the time complexity significantly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize two pointers to track the length of the increasing and decreasing sequences.
  2. 2Step 2: Traverse the array while checking for peaks and counting lengths of increasing and decreasing sequences.
  3. 3Step 3: Whenever a peak is found, calculate the total length and update the maximum length.
solution.py19 lines
1# Full working Python code
2
3def longestMountain(arr):
4    n = len(arr)
5    max_length = 0
6    i = 1
7    while i < n - 1:
8        if arr[i - 1] < arr[i] > arr[i + 1]:  # Peak check
9            left = i - 1
10            right = i + 1
11            while left > 0 and arr[left - 1] < arr[left]:
12                left -= 1
13            while right < n - 1 and arr[right] > arr[right + 1]:
14                right += 1
15            max_length = max(max_length, right - left + 1)
16            i = right  # Move to the end of the mountain
17        else:
18            i += 1
19    return max_length

Complexity note: The time complexity is O(n) because we only make a single pass through the array, checking each element once. The space complexity is O(1) since we use a constant amount of extra space.

  • 1A mountain must have a peak with elements strictly increasing before and strictly decreasing after it.
  • 2The longest mountain can be found by efficiently tracking peaks and their boundaries.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.