#1671
Minimum Number of Removals to Make Mountain Array
HardArrayBinary SearchDynamic ProgrammingGreedyDynamic ProgrammingLongest Increasing Subsequence
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
Instead of removing elements, we can find the longest mountain subsequence using dynamic programming. We will first find the longest increasing subsequence (LIS) from the left and then from the right, and combine the results to find the longest mountain.
⚙️
Algorithm
5 steps- 1Step 1: Create two arrays, left and right, to store the length of the longest increasing subsequence up to each index from the left and right respectively.
- 2Step 2: Fill the left array using a modified LIS approach.
- 3Step 3: Fill the right array using a similar approach but from the right side.
- 4Step 4: For each index, calculate the length of the mountain using left[i] + right[i] - 1 (to avoid double counting the peak).
- 5Step 5: Find the maximum length of the mountain and subtract it from the total length to get the minimum removals.
solution.py29 lines
1# Full working Python code
2
3def min_removals_to_make_mountain(nums):
4 n = len(nums)
5 if n < 3:
6 return 0
7
8 left = [1] * n
9 right = [1] * n
10
11 # Fill left array
12 for i in range(1, n):
13 for j in range(i):
14 if nums[i] > nums[j]:
15 left[i] = max(left[i], left[j] + 1)
16
17 # Fill right array
18 for i in range(n - 2, -1, -1):
19 for j in range(n - 1, i, -1):
20 if nums[i] > nums[j]:
21 right[i] = max(right[i], right[j] + 1)
22
23 max_length = 0
24 for i in range(1, n - 1):
25 if left[i] > 1 and right[i] > 1:
26 max_length = max(max_length, left[i] + right[i] - 1)
27
28 return n - max_length
29ℹ
Complexity note: The time complexity is O(n²) due to the nested loops used to fill the left and right arrays, while the space complexity is O(n) for storing the lengths of the subsequences.
- 1Finding the longest mountain subsequence is crucial to minimizing removals.
- 2Dynamic programming can efficiently solve the problem by breaking it down into smaller subproblems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.