MediumNo. 0845

Longest Mountain in Array — LeetCode 845 Python Solution

Topics
Array, Two Pointers, Dynamic Programming, Enumeration
Reading time
3 min

The problem

You may recall that an array arr is a mountain array if and only if: arr.length >= 3 There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ...

Example

Input
arr = [2,1,4,7,3,2,5]
Output
5
Explanation
The largest mountain is [1,4,7,3,2] which has length 5.

Python solution

PythonSolution
class Solution:
    def longestMountain(self, arr: List[int]) -> int:
        n = len(arr)
        f = [1] * n
        g = [1] * n
        for i in range(1, n):
            if arr[i] > arr[i - 1]:
                f[i] = f[i - 1] + 1
        ans = 0
        for i in range(n - 2, -1, -1):
            if arr[i] > arr[i + 1]:
                g[i] = g[i + 1] + 1
                if f[i] > 1:
                    ans = max(ans, f[i] + g[i] - 1)
        return ans

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 845. Longest Mountain in Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
2970Count the Number of Incremovable Subarrays IEasy
0838Push DominoesMedium
0005Longest Palindromic SubstringMedium
00153SumMedium
00163Sum ClosestMedium
00184SumMedium

Frequently asked questions

How hard is LeetCode 845. Longest Mountain in Array?

LeetCode 845. Longest Mountain in Array is rated Medium on LeetCode.

What is the time complexity of LeetCode 845. Longest Mountain in Array?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 845. Longest Mountain in Array?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 845. Longest Mountain in Array cover?

LeetCode 845. Longest Mountain in Array is tagged Array, Two Pointers, Dynamic Programming and Enumeration on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.