Minimum Number of Removals to Make Mountain Array — LeetCode 1671 Python Solution

HardGreedyArrayBinary SearchDynamic Programming
Problem
#1671
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
nums = [1,3,1]
Output
0
Explanation
The array itself is a mountain array so we do not need to remove any elements.

Python solution

Python
class Solution:
    def minimumMountainRemovals(self, nums: List[int]) -> int:
        n = len(nums)
        left = [1] * n
        right = [1] * n
        for i in range(1, n):
            for j in range(i):
                if nums[i] > nums[j]:
                    left[i] = max(left[i], left[j] + 1)
        for i in range(n - 2, -1, -1):
            for j in range(i + 1, n):
                if nums[i] > nums[j]:
                    right[i] = max(right[i], right[j] + 1)
        return n - max(a + b - 1 for a, b in zip(left, right) if a > 1 and b > 1)

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 1671. Minimum Number of Removals to Make Mountain Array is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1671. Minimum Number of Removals to Make Mountain Array?
LeetCode 1671. Minimum Number of Removals to Make Mountain Array is rated Hard on LeetCode.
What is the time complexity of LeetCode 1671. Minimum Number of Removals to Make Mountain Array?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 1671. Minimum Number of Removals to Make Mountain Array?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1671. Minimum Number of Removals to Make Mountain Array cover?
LeetCode 1671. Minimum Number of Removals to Make Mountain Array is tagged Greedy, Array, Binary Search and Dynamic Programming 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.

Get Stealth Interview