Minimum Number of Removals to Make Mountain Array - 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] > ... > arr[arr.length - 1]

Given an integer array nums, return the minimum number of elements to remove to make nums a mountain array.

Input & Output

Example 1 — Basic Mountain
$ Input: nums = [1,3,1]
Output: 0
💡 Note: The array [1,3,1] is already a mountain array with peak at index 1: 1 < 3 > 1. No removals needed.
Example 2 — Need Removals
$ Input: nums = [2,1,1,5,6,2,3,1]
Output: 3
💡 Note: We can form mountain [2,5,6,3,1] by removing elements at indices 1, 2, and 7. This gives us 8 - 5 = 3 removals.
Example 3 — Small Array
$ Input: nums = [4,3,2,1,1,2,3,1]
Output: 4
💡 Note: We can form mountain [1,2,3,1] from the latter part. This requires removing 4 elements.

Constraints

  • 3 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Minimum Removals to Make Mountain Array INPUT nums = [1, 3, 1] 1 i=0 3 i=1 1 i=2 Mountain Shape: 1 Peak: 3 1 increasing decreasing Length: 3 (valid) Peak at index 1 ALGORITHM STEPS 1 Compute LIS left Longest Increasing Subseq left = [1, 2, 1] 2 Compute LIS right Longest Decreasing (rev) right = [1, 2, 1] 3 Find max mountain Where left[i]>1 AND right[i]>1 mountain[1] = 2+2-1 = 3 4 Calculate removals removals = n - max_mountain removals = 3 - 3 = 0 DP Tables idx: 0 1 2 left: 1 2 1 right: 1 2 1 FINAL RESULT Original array is already a valid mountain! 1 3 1 PEAK OK Output: 0 No elements need removal 1 < 3 > 1 is valid Key Insight: Use Dynamic Programming with two LIS arrays: one from left (increasing) and one from right (decreasing). For each valid peak i where left[i] > 1 AND right[i] > 1, the mountain length = left[i] + right[i] - 1. Answer = n - max(mountain lengths). Time: O(n^2), Space: O(n). TutorialsPoint - Minimum Number of Removals to Make Mountain Array | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen